Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Functional Programming in Cakephp

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 227
    Comment on it

    CakePhp supports functional programming. Functional Programming in CakePhp is a criterion as are crucial, logical and Object Oreinted programming. In CakePhp everything resides inside a function, in the mathematical sense. The
    consequence of that you will not face any side effect since everthing depends merely on the input of the function. It means that you cannot have any inconsistent state, once you compute something, you cannot  change it to something else.

    Function in Php

    Functions are important part in the Php 

    
    // Function which are used as a variable
    $func = function() {
      return 42;
    };
     
    // Function which are used as a return type
    function createFunction() {
      return function() { return "Thanks"; };
    };
    $func2 = createFunction();
     
    // Function as a parameter
    function display($func) {
      echo $func()."\n\n";
    }
     
    // Call a function by name
    call_user_func_array('strtoupper', $someString);
     
    // objects as functions
    class SomeClass {
    public function __invoke($param1, $param2) {
    [...]
    }
    }
    $instance = new SomeClass();
    $instance('First', 'Second'); // call the __invoke() method
    

    Mapping

    After creating the functions we will do the mapping between the functions. We manipulate the array using mapping.

    // The crucial way :
     
    foreach($stringArray as $k => $v) {
      $stringArray[$k] = strtoupper($v);
    }
    // The functional way :
     
    $result = array_map('strtoupper', $stringArray);

    Reducing

    Reducing an array, sometimes called “fold” in functional languages :

    // The crucial way :
     
    $result = 0;
    foreach($intArray as $v) {
      $result += $v;
    }
    // The functional way :
     
    $result = array_reduce($intArray, function($a, $b) { return $a + $b; }, 0)

    Filtering

    Filtering is used to filter the array

    // The crucail way :
     
    $result = array();
    foreach($intArray as $v) {
      if($v % 2 === 0) {
        $result[] = $v;
      }
    }
    // The functional way :
     
    $result = array_filter($intArray, function($a) { return ($a % 2 === 0); })
     

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: