Functional style programming with Underscore.php

Underscore.php is a PHP port of the popular Underscore.js library. Underscore.php provides a utility library for PHP that provides a lot of the functional programming support that a programmer would expect in Ruby, but without adding much overhead during execution. The only caveat is that underscore.php requires PHP 5.3 or greater. Although you could accomplish some of the things using PHP’s built in functions, the functional style approach looks intuitive and easy to work with. Note that this not a purely functional programming like Haskell. It would be nice to integrate the library in your CakePHP framework, which will help bring some functional flavor to the framework.

Take a quick example of the ‘pluck’ method.

include_once('underscore.php');
 
$members= array(
  array('name'=>'bill', 'age'=>40, 'gender' => 'm'),
  array('name'=>'john', 'age'=>50, 'gender' => 'm'),
  array('name'=>'sarah','age'=>60, 'gender' => 'f')
);
 
$ret = __::pluck($members, 'name');
print_r($ret);

(more…)

Read More