Skip to content
Ihor Burlachenko edited this page May 19, 2016 · 4 revisions

Non-standard PHP Library (NSPL) is a collection of modules that are meant to solve common day to day routine problems:

  • nspl\f - provides functions that act on other functions. Helps to write code in functional programming paradigm
  • nspl\op - provides functions that perform standard PHP operations and can be passed as callbacks to higher-order functions. Mimics Python's operator module
  • nspl\a - provides missing array functions which also can be applied to traversable sequences
  • nspl\args - helps to validate function arguments
  • nspl\ds - provides non-standard data structures and methods to work with them
  • nspl\rnd - helps to pick random items from sequences of data

NSPL aims to make code compact and less verbose but still clear and readable. Look at the following example:

// get user ids
$userIds = map(propertyGetter('id'), $users);

// or sort them by age
$sortedByAge = sorted($users, methodCaller('getAge'));

// or check if they all are online
$online = all($users, methodCaller('isOnline'));

// or define new function as composition of the existing ones
$flatMap = compose(rpartial(flatten, 1), map);

In pure PHP it would look like this:

// get user ids
$userIds = array_map(function($user) { return $user->id; }, $users);

// sort them by age, note that the following code modifies the original users array
usort($users, function($user1, $user2) {
    return $user1->getAge() - $user2->getAge();
});

// check if they all are online
$online = true;
foreach ($users as $user) {
    if (!$user->isOnline()) {
        $online = false;
        break;
    }
}

// define new function as composition of the existing ones
$flatMap = function($function, $list) {
    // note the inconsistency in array_map and array_reduce parameters
    return array_reduce(array_map($function, $list), 'array_merge', []);
};

You can see more examples in the library reference below or here.

Clone this wiki locally