PHP lacks consistency, that's a fact. Many functions within a similar field — for instance array functions — may have inconsistent names and prototypes. Underscore.php aims to correct that by providing simple, consistent and data-type tolerant 80-odd functions that support both the usual functional suspects: map, select, invoke — as well as more specialized helpers: function binding, php templating, deep equality testing, and so on.
Underscore.php is strongly inspired by Underscore.js and try to be consistent with it as much as possible (PHP language limitation doesn't allow full coverage — especialy for Functions functions...) Don't hesitate to report any discrepancy with Underscore.js.
- Made with ♥ for PHP 5.4+
- Type tolerant
- Triggers exceptions instead of errors
- Consistent function names / arguments
- Hassle-free chaining
- ERB-style templating
- Extensible
This library is in beta phase: you are strongly encouraged to try it and to contribute.Feel free to file an issue if you encounter a bug or an unexpected result.
Juggling with types in PHP can be tedious. Not only types are sometimes ambiguous, they don't fit in every API function/method. For instance, if you want to map every item from an iterator using array_map, you have to translate it into an array first or write the mapping yourself using a loop. Same goes for sort, diff or filter...
PHP is loosely typed, which means that the data you're manipulating are more important than their structure. Underscore.php understands that by providing a comprehensive interface that works with almost every data-type so you don't have to worry about whether you can or cannot use a function/method.
Basically, Underscore.php uses 3 main data-types:
- Scalar (integer, float, boolean, or string)
- Traversable (array, object, or iterator)
- Callable (closure, function, method, or runtime-created function)
When a fuction requires a Traversable as argument, you can provide either an array, an instance of stdClass — the default (object)
casting — an Iterator or anything that implements the Traversable interface, such as a PDOStatement object. With certain functions like #extend, you can even extend an array with an object instance and everything will be fine.
<?php
// let's merge our configuration object with data from $_SESSION and MySQL
$userConfig = _::extend([],
include "global.conf.php", // is an array
$pdo->query($groupConfigurationQuery) // is a PDOStatement
$_SESSION['user']->configuration, // is an object
);
?>
- Installation
- Usage
- Collection Functions
- Uncategorized
- Array Functions
- first, initial, last, rest, compact, flatten, without, uniq, union, intersection, difference, zip, obj, indexOf, lastIndexOf, sortedIndex, range
- Function (uh, ahem) Functions
- Object Functions
- keys, values, pairs, invert, functions, extend, pick, omit, defaults, duplicate, tap, has, property, matches, get, set, is, isEqual, isEmpty, isArray, isObject, isFunction, isNumber, isInteger, isFloat, isString, isDate, isRegExp, isFinite, isNaN, isBoolean, isNull, isScalar, isTraversable, isResource, typeOf
- Utility Functions
- Chaining
- Class Forgery
Add the following require rule to composer.json and run composer update
. See the Packagist repository for more details.
require: { "bdelespierre/underscore": "dev-master" }
git clone https://github.com/bdelespierre/underscore.php ./underscore.php
curl -sS https://github.com/bdelespierre/underscore.php/archive/master.zip > underscore.php.zip
unzip underscore.php.zip && rm underscore.zip
Or simply download the zip and extract it where you want.
<?php
require_once "vendor/autoload.php";
use Underscore\Underscore as _;
_::each([1,2,3], function ($i) { echo "{$i}\n"; });
?>
<?php
require_once "path/to/underscore/src/Underscore/Underscore.php";
require_once "path/to/underscore/src/Underscore/Bridge.php";
use Underscore\Underscore as _;
_::each([1,2,3], function ($i) { echo "{$i}\n"; });
?>
Underscore functions can also be used as procedural functions. To do so, include the functions.php
library. The only limitation is that you cannot dynamically add new functions with _::mixin
.
<?php
require_once "path/to/underscore/src/functions.php";
_each([1,2,3], function ($i) { echo "{$i}\n"; });
?>
- each
- eachReference
- map
- reduce
- reduceRight
- find
- filter
- where
- findWhere
- reject
- every
- some
- contains
- invoke
- pluck
- max
- min
- sortBy
- indexBy
- groupBy
- countBy
- shuffle
- sample
- toArray
- size
Description: Iterates over a list of elements, yielding each in turn to an iterator function. The iterator is bound to the context object, if one is passed. Each invocation of iterator is called with three arguments: (element, index, list). If list is an object, iterator's arguments will be (value, key, list).
- list: traversable, the list to iterate over
- iterator: callable, the iteration function
- context: object, optional, if provided will become the context of $iterator
_::each(list,iterator,context)
<?php
_::each([1,2,3], function ($i) { echo $i; });
// => 123
_::each((object)['a'=>1,'b'=>2,'c'=>3], function ($value, $key) { echo "$key => $value\n"; });
// => displays each pair in turn
?>
Table of contents » Collection Functions
Alias: walk
Description: Does the very same job as each but provide a reference of every list item to the iterator function.
- list: traversable, the list to iterate over
- iterator: callable, the iteration function
- context: object, optional, if provided will become the context of $iterator
_::eachReference(list,iterator,context)
<?php
$numbers = [1,2,3];
_::eachReference($numbers, function (& $value) { $value *= $value; });
// => [1,4,9]
?>
Table of contents » Collection Functions
Alias: collect
Description: Produces a new array of values by mapping each value in list through a transformation function (iterator). The iterator is bound to the context object, if one is passed. Each invocation of iterator is called with three arguments: (element, index, list). If list is an object, iterator's arguments will be (value, key, list).
- list: traversable, the list of items to map
- iterator: callable, the transformation function
- context: object, optional, if provided will become the context of $iterator
_::map(list,iterator,context)
<?php
_::map([1,2,3], function ($value) { return $value -1; });
// => [0,1,2]
?>
Table of contents » Collection Functions
Alias: inject, foldl
Description: Also known as inject and foldl, reduce boils down a list of values into a single value. Memo is the initial state of the reduction, and each successive step of it should be returned by iterator. The iterator is passed four arguments: the memo, then the value and index (or key) of the iteration, and finally a reference to the entire list.
- list: traversable, the list of items to reduce
- iterator: callable, the reduction function
- memo: mixed, The initial reduction state
- context: object, optional, if provided will become the context of $iterator
_::reduce(list,iterator,memo,context)
<?php
$sum = _::reduce([1,2,3], function ($memo, $num) { return $memo + $num; }, 0);
// => 6
?>
Table of contents » Collection Functions
Alias: foldr
Description: The right-associative version of reduce.
- list: traversable, the list of items to reduce
- iterator: callable, the reduction function
- memo: mixed, The initial reduction state
- context: object, optional, if provided will become the context of $iterator
_::reduceRight(list,iterator,memo,context)
<?php
$list = [[0, 1], [2, 3], [4, 5]];
$flat = _::reduceRight($list, function ($a, $b) { return array_merge($a, $b); }, []);
// => [4,5,2,3,0,1]
?>
Table of contents » Collection Functions
Alias: detect
Description: Looks through each value in the list, returning the first one that passes a truth test (iterator), or null if no value passes the test. The function returns as soon as it finds an acceptable element, and doesn't traverse the entire list.
- list: traversable, the list of items to iterate over
- iterator: callable, the truth-test function
- context: object, optional, if provided will become the context of $iterator
_::find(list,iterator,context)
<?php
$even = _::find([1,2,3,4,5,6], function ($num) { return $num % 2 == 0; });
// => 2
?>
Table of contents » Collection Functions
Alias: select
Description: Looks through each value in the list, returning an array of all the values that pass a truth test (iterator). If iterator isn't provided, each value will be evaluated as a boolean.
- list: traversable, the list of items to filter
- iterator: callable, the filtering function
- context: object, optional, if provided will become the context of $iterator
_::filter(list,iterator,context)
<?php
$evens = _::filter([1,2,3,4,5,6], function ($num) { return $num % 2 == 0; });
// => [2,4,6]
?>
Table of contents » Collection Functions
Description: Looks through each value in the list, returning an array of all the values that contain all of the key-value pairs listed in properties.
- list: traversable, the list of items to filter
- properties: traversable, the key-values pairs each filtered item must match
_::where(list,properties)
<?php
$people = [
['name' => 'Jack Nicholson', 'born' => 1937, 'profession' => 'actor'],
['name' => 'Morgan Freeman', 'born' => 1937, 'profession' => 'actor'],
['name' => 'Leonardo Dicaprio', 'born' => 1974, 'profession' => 'actor'],
['name' => 'Nathalie Portman', 'born' => 1981, 'profession' => 'actor'],
['name' => 'Ridley Scott', 'born' => 1937, 'profession' => 'producer'],
];
$actorsBornIn1937 = _::where($people, ['born' => 1937, 'profession' => 'actor']);
// => Jack Nicholson & Morgan Freeman
?>
Table of contents » Collection Functions
Description: Looks through the list and returns the first value that matches all of the key-value pairs listed in properties.
- list: traversable, the list of items to filter
- properties: traversable, the key-values pairs each filtered item must match
_::findWhere(list,properties)
<?php
$people = [
['name' => 'Jack Nicholson', 'born' => 1937, 'profession' => 'actor'],
['name' => 'Morgan Freeman', 'born' => 1937, 'profession' => 'actor'],
['name' => 'Leonardo Dicaprio', 'born' => 1974, 'profession' => 'actor'],
['name' => 'Nathalie Portman', 'born' => 1981, 'profession' => 'actor'],
['name' => 'Ridley Scott', 'born' => 1937, 'profession' => 'producer'],
];
$actor = _::findWhere($people, ['born' => 1937, 'profession' => 'actor']);
// => Jack Nicholsonn
?>
Table of contents » Collection Functions
Description: Returns the values in list without the elements that the truth test (iterator) passes. The opposite of filter.
- list: traversable, the list of items to filter
- iterator: callable, the truth-test function
- context: object, optional, if provided will become the context of $iterator
_::reject(list,iterator,context)
<?php
$odds = _::reject([1,2,3,4,5,6], function ($num) { return $num % 2 == 0; });
// => [1,3,5]
?>
Table of contents » Collection Functions
Alias: all
Description: Returns true if all of the values in the list pass the iterator truth test. Short-circuits and stops traversing the list if a false element is found.
- list: traversable, the list of items to filter
- iterator: callable, the truth-test function
- context: object, optional, if provided will become the context of $iterator
_::every(list,iterator,context)
<?php
_::every([true, 1, null, 'yes']);
// => false
?>
Table of contents » Collection Functions
Alias: any
Description: Returns true if any of the values in the list pass the iterator truth test. Short-circuits and stops traversing the list if a true element is found.
- list: traversable, the list of items to filter
- iterator: callable, the truth-test function
- context: object, optional, if provided will become the context of $iterator
_::some(list,iterator,context)
<?php
_::some([null, 0, 'yes', false]);
// => true
?>
Table of contents » Collection Functions
Alias: includes
Description: Returns true if the value is present in the list.
- list: traversable, the list of items
- value: mixed, the value to look for
- strict: boolean, type of value is also used in coparision
_::contains(list,value,strict)
<?php
_::contains([1,2,3], 3);
// => true
?>
Table of contents » Collection Functions
Description: Calls the method named by methodName on each value in the list. Any extra arguments passed to invoke will be forwarded on to the method invocation. If your list items are arrays (instead of objects) methods from ArrayObject can be used (like asort). If the wanted method is not found on the current item during iteration, the item will be left untouched.
- list: traversable, the list of items to invoke method/function onto
- methodName: callable,string, the name of the method to invoke or a closure
- arguments: array, the method's arguments
_::invoke(list,methodName,arguments)
<?php
_::invoke([[5, 1, 7], [3, 2, 1]], 'sort');
// => [[1, 5, 7], [1, 2, 3]
?>
Table of contents » Collection Functions
Description: A convenient version of what is perhaps the most common use-case for map: extracting a list of property values.
- list: traversable, the list of items
- propertyName: string, the name of the property to extract from each item
_::pluck(list,propertyName)
<?php
$stooges = [
['name' => 'moe', 'age' => 40],
['name' => 'larry', 'age' => 50],
['name' => 'curly', 'age' => 60]
];
_::pluck($stooges, 'name');
// => ['moe','larry','curly']
?>
Table of contents » Collection Functions
Description: Returns the maximum value in list. If iterator is passed, it will be used on each value to generate the criterion by which the value is ranked.
- list: traversable, the list of items
- iterator: callable, optional, the comparision function
- context: object, optional, if provided will become the context of $iterator
_::max(list,iterator,context)
<?php
$stooges = [
['name' => 'moe', 'age' => 40],
['name' => 'larry', 'age' => 50],
['name' => 'curly', 'age' => 60]
];
_::max($stooges, function($stooge) { return $stooge['age']; });
// => 60
?>
Table of contents » Collection Functions
Description: Returns the minimum value in list. If iterator is passed, it will be used on each value to generate the criterion by which the value is ranked.
- list: traversable, the list of items
- iterator: mixed, no description available...
- context: object, optional, if provided will become the context of $iterator
_::min(list,iterator,context)
<?php
$numbers = [10, 5, 100, 2, 10000];
_::min($numbers);
// => 2
?>
Table of contents » Collection Functions
Description: Returns a (stably) sorted copy of list, ranked in ascending order by the results of running each value through iterator. Returns NULL in case of error.
- list: traversable, the list of items to sort
- iterator: callable, the function that generates the criteria by which items are sorted
- context: object, optional, if provided will become the context of $iterator
_::sortBy(list,iterator,context)
<?php
_::sortBy([1, 2, 3, 4, 5, 6], function($num) { return sin($num); });
// => [5, 4, 6, 3, 1, 2]
?>
Table of contents » Collection Functions
Description: Given a list, and an iterator function that returns a key for each element in the list (or a property name), returns an object with an index of each item. Just like groupBy, but for when you know your keys are unique.
- list: traversable, the list of items to index
- iterator: callable,scalar, the function to generate the key or a property name
- context: object, optional, if provided will become the context of $iterator
_::indexBy(list,iterator,context)
<?php
$stooges = [
['name' => 'moe', 'age' => 40],
['name' => 'larry', 'age' => 50],
['name' => 'curly', 'age' => 60]
];
_::indexBy($stooges, 'age');
// => [
// "40" => ['name' => 'moe', 'age' => 40],
// "50" => ['name' => 'larry', 'age' => 50],
// "60" => ['name' => 'curly', 'age' => 60]
// ]
?>
Table of contents » Collection Functions
Description: Splits a collection into sets, grouped by the result of running each value through iterator. If iterator is a string instead of a function, groups by the property named by iterator on each of the values.
- list: traversable, the list of items to group
- iterator: callable,scalar, the function to generate the key or a property name
- context: object, optional, if provided will become the context of $iterator
_::groupBy(list,iterator,context)
<?php
_::groupBy([1.3, 2.1, 2.4], function($num) { return floor($num); });
// => [1 => [1.3], 2 => [2.1, 2.4]]
$values = [
['val' => 'one', 'length' => 3],
['val' => 'two', 'length' => 3],
['val' => 'three', 'length' => 5]
];
_::groupBy($values, 'length');
// => [3 => [['val' => 'one', 'lenght' => 3], ['val' => 'two', 'length' => 3], 5 => [['val' => 'three', 'length' => 5]]]
?>
Table of contents » Collection Functions
Description: Sorts a list into groups and returns a count for the number of objects in each group. Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group.
- list: traversable, the list of items to group and count
- iterator: callable,scalar, the function to generate the key or a property name
- context: object, optional, if provided will become the context of $iterator
_::countBy(list,iterator,context)
<?php
_::countBY([1, 2, 3, 4, 5], function($num) {
return $num % 2 == 0 ? 'even' : 'odd';
});
// => ['odd' => 3, 'even' => 2]
?>
Table of contents » Collection Functions
Description: Returns a shuffled copy of the list.
- list: traversable, the list of items to shuffle
_::shuffle(list)
<?php
_::shuffle([1, 2, 3, 4, 5, 6]);
// => [4, 1, 6, 3, 5, 2]
?>
Table of contents » Collection Functions
Description: Produce a random sample from the list. Pass a number to return n random elements from the list. Otherwise a single random item will be returned.
- list: traversable, the list of items
- n: int, optional, the number of items to pick
_::sample(list,n)
<?php
_::sample([1, 2, 3, 4, 5, 6]);
// => 4
_::sample([1, 2, 3, 4, 5, 6], 3);
// => [1, 6, 2]
?>
Table of contents » Collection Functions
Description: Creates a real Array from the list (anything that can be iterated over). This method will also accept scalars such as string, number and even null and will cast them into arrays, for instance Underscore::toArray(null) is [] altough Underscore::toArray('a') is ['a'].
- list: traversable, the list of items
_::toArray(list)
<?php
$object = new stdClass;
$object->one = 1;
$object->two = 2;
$object->three = 3;
_::toArray($object);
// => ['one' => 1, 'two' => 2, 'three' => 3]
_::toArray(null);
// => []
_::toArray("hello");
// => ["hello"]
?>
Table of contents » Collection Functions
Description: Return the number of values in the list. This method will also accept scalars such as string, number and even null or resources but will return 1 in that case.
- list: traversable, the list of items
_::size(list)
<?php
$object = new stdClass;
$object->one = 1;
$object->two = 2;
$object->three = 3;
_::size($object);
// => 3
?>
Table of contents » Collection Functions
Description: Split a collection into two arrays: one whose elements all satisfy the given predicate, and one whose elements all do not satisfy the predicate.
- list: traversable, the list of items
- iterator: callable, the predicate
- context: object, optional, if provided will become the context of $iterator
_::partition(list,iterator,context)
<?php
_::partition([0, 1, 2, 3, 4, 5], function($num) { return $num % 2 != 0; });
// => [[1, 3, 5], [0, 2, 4]]
?>
Table of contents » Uncategorized
Description: Returns an integer timestamp for the current time.
_::now()
Table of contents » Uncategorized
- first
- initial
- last
- rest
- compact
- flatten
- without
- uniq
- union
- intersection
- difference
- zip
- obj
- indexOf
- lastIndexOf
- sortedIndex
- range
Alias: head, take
Description: Returns the first element of an array. Passing n will return the first n elements of the array. Passing guard will force the returned value to be an array.
- array: traversable, the list of items
- n: int, optional, the number of items to pick
- guard: bool, optional, true to always return an array
_::first(array,n,guard)
Table of contents » Array Functions
Description: Returns everything but the last entry of the array. Pass n to exclude the last n elements from the result. Passing guard will force the returned value to be an array.
- array: traversable, the list of items
- n: int, optional, the number of items to exclude
- guard: bool, optional, true to always return an array
_::initial(array,n,guard)
Table of contents » Array Functions
Description: Returns the last element of an array. Passing n will return the last n elements of the array. Passing guard will force the returned value to be an array.
- array: traversabel, the list of items
- n: int, optional, the number of items to pick
- guard: bool, optional, true to always return an array
_::last(array,n,guard)
Table of contents » Array Functions
Alias: tail, drop
Description: Returns the rest of the elements in an array. Pass an index to return the values of the array from that index onward. Passing guard will force the returned value to be an array.
- array: traversable, the list of items
- index: int, optional, the index from which the items are picked
- guard: bool, optional, true to always return an array
_::rest(array,index,guard)
Table of contents » Array Functions
Description: Returns a copy of the array with all falsy values removed. In PHP, false, null, 0, "", array() and "0" are all falsy.
- array: traversable, the list of items
_::compact(array)
Table of contents » Array Functions
Description: Flattens a nested array (the nesting can be to any depth). If you pass shallow, the array will only be flattened a single level.
- array: traversable, the list of items
- shallow: bool, optional, if true will only flatten on single level
_::flatten(array,shallow)
Table of contents » Array Functions
Description: Returns a copy of the array with all instances of the values removed.
- array: traversable, the list of items
- values: array,mixed, multiple, the value(s) to exclude
_::without(array,values)
Table of contents » Array Functions
Alias: unique
Description: Produces a duplicate-free version of the array, using === to test object equality. If you know in advance that the array is sorted, passing true for isSorted will run a much faster algorithm. If you want to compute unique items based on a transformation, pass an iterator function. WARNING: this function's cyclomatic complexity is (at least) quadratic ! using it with large arrays (> 1000 items) can be very slow and memory consuming.
- array: traversable, the list of items
- isSorted: bool, optional, use a faster algorithm if the list is already sorted
- iterator: callable, optional, the comparision function if needed
- context: object, optional, if provided will become the context of $iterator
_::uniq(array,isSorted,iterator,context)
Table of contents » Array Functions
Description: Computes the union of the passed-in arrays: the list of unique items, in order, that are present in one or more of the arrays.
- array: traversable, multiple, the arrays to join
_::union(array)
Table of contents » Array Functions
Description: Computes the list of values that are the intersection of all the arrays. Each value in the result is present in each of the arrays.
- array: traversable, multiple, the arrays to intersect
_::intersection(array)
Table of contents » Array Functions
Description: Similar to without, but returns the values from array that are not present in the other arrays.
- array: traversable, multiple, the arrays to difference
_::difference(array)
Table of contents » Array Functions
Description: Merges together the values of each of the arrays with the values at the corresponding position. Useful when you have separate data sources that are coordinated through matching array indexes.
- array: traversable, multiple, the arrays to zip
_::zip(array)
Table of contents » Array Functions
Description: Converts arrays into objects. Pass either a single list of [key, value] pairs, or a list of keys, and a list of values. If duplicate keys exist, the last value wins.
- list: array, the properties
- values: array, optional, the values, if not provided each item of $list is used a pair
_::obj(list,values)
Table of contents » Array Functions
Description: Returns the index at which value can be found in the array, or -1 if value is not present in the array. This method uses array_search internally and is not optimized for long array binary search.
- array: traversable, the list of items
- item: mixed, the value to look for
_::indexOf(array,item)
Table of contents » Array Functions
Description: Returns the index of the last occurrence of value in the array, or -1 if value is not present. This method uses array_keys internally and is not optimized for long array binary search.
- array: traversable, the list of items
- item: mixed, the value to look for
_::lastIndexOf(array,item)
Table of contents » Array Functions
Description: Uses a binary search to determine the index at which the value should be inserted into the list in order to maintain the list's sorted order. If an iterator is passed, it will be used to compute the sort ranking of each value, including the value you pass. Iterator may also be the string name of the property to sort by (eg. length).
- array: traversable, the list of items
- value: mixed, the value to find the index for
- iterator: callable,scalar, optional, the function by which a value is evaluated or a property's name
- context: object, optional, if provided will become the context for $iterator
_::sortedIndex(array,value,iterator,context)
Table of contents » Array Functions
Description: A function to create flexibly-numbered lists of integers, handy for each and map loops. start, if omitted, defaults to 0; step defaults to 1. Returns a list of integers from start to stop, incremented (or decremented) by step, exclusive. This method uses range internally.
- start: int, the starting index
- stop: int, optional, the ending index
- step: int, optional, the iteration step
_::range(start,stop,step)
Table of contents » Array Functions
Description: Wrap the first function inside of the wrapper function, passing it as the first argument. This allow the wrapper to execute code before and after the function runs, adjust the arguments and execute it conditionnaly. Arguments are passed along to the wrapper function.
- function: callable, the function
- wrapper: mixed, no description available...
_::wrap(function,wrapper)
Table of contents » Function (uh, ahem) Functions
Description: Returns a new negated version of the predicate function.
- function: callable, the function
_::negate(function)
Table of contents » Function (uh, ahem) Functions
Description: Returns the composition of a list of functions, where each function consumes the return value of the function that follows. In math terms, composing the functions f(), g(), and h() produces f(g(h())).
- functions: callable, multiple, the functions to compose
_::compose(functions)
Table of contents » Function (uh, ahem) Functions
Description: Creates a version of the function that will only be run after first being called count times. Please note that the function shall not recieve parameters.
- count: int, the number of times the $function shall be executed
- function: callable, the function
_::after(count,function)
Table of contents » Function (uh, ahem) Functions
Description: Creates a version of the function that can be called no more than count times. The result of the last function call is memoized and returned when count has been reached.
- count: int, the number of times the $function shall be executed
- function: callable, the function
_::before(count,function)
Table of contents » Function (uh, ahem) Functions
Description: Creates a version of the function that can only be called one time. Repeated calls to the modified function will have no effect, returning the value from the original call. Useful for initialization functions, instead of having to set a boolean flag and then check it later.
- function: callable, the function
_::once(function)
Table of contents » Function (uh, ahem) Functions
Description: Partially apply a function by filling in any number of its arguments. Not all the arguments have to be present on the partial construction.
- function: callable, the function
- arguments: array,mixed, multiple, the arguments
_::partial(function,arguments)
Table of contents » Function (uh, ahem) Functions
Description: Bind a function to an object, meaning that whenever the function is called, the value of $this will be the object. Optionally, pass arguments to the function to pre-fill them, also known as partial application.
- function: closure, the function
- object: object, the object to bind the closure to
_::bind(function,object)
Table of contents » Function (uh, ahem) Functions
Description: Bind a function to a class, meaning that whenever the function is called, the value of self or static will be the class. Optionally, pass arguments to the function to pre-fill them, also known as partial application.
- function: closure, the function
- class: object,string, the object or classname to bind the closure to
_::bindClass(function,class)
Table of contents » Function (uh, ahem) Functions
Description: Binds a number of methods on the object, specified by methodNames, to be run in the context of that object whenever they are invoked. Very handy for binding functions that are going to be used as event handlers, which would otherwise be invoked with a fairly useless this. methodNames are required. Keep in mind PHP doesn't allow to call a closure property value like a method, for instance $o->myClosure(), given $o is an instance of stdClass, won't work.
- object: object, the object
- methodNames: array,callable, multiple, the functions to attach
_::bindAll(object,methodNames)
Table of contents » Function (uh, ahem) Functions
Description: Memoizes a given function by caching the computed result. Useful for speeding up slow-running computations. If passed an optional hashFunction, it will be used to compute the hash key for storing the result, based on the arguments to the original function. The default hashFunction just uses the first argument to the memoized function as the key.
- function: callable, the function to memoize
- hashFunction: callable, optional, if provided will be used to hash $function's results
- cache: array,ArrayAccess, optional, function's results cache
_::memoize(function,hashFunction,cache)
Table of contents » Function (uh, ahem) Functions
Description: Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, will only actually call the original function at most once per every wait milliseconds. Useful for rate-limiting events that occur faster than you can keep up with.
- function: callable, the function
- wait: int, the time to wait between each call (in milliseconds)
_::throttle(function,wait)
Table of contents » Function (uh, ahem) Functions
Description: Call (execute) the given function, optionnaly bound to $context, with the given arguments and return its result.
- function: callable, the function
- context: object, the function's context
_::call(function,context)
Table of contents » Function (uh, ahem) Functions
Description: Call (execute) the given function, optionnaly bound to $context, with the given argument list and return its result.
- function: callable, the function
- context: object, the function's context
- arguments: list, the arguments
_::apply(function,context,arguments)
Table of contents » Function (uh, ahem) Functions
- keys
- values
- pairs
- invert
- functions
- extend
- pick
- omit
- defaults
- duplicate
- tap
- has
- property
- matches
- get
- set
- is
- isEqual
- isEmpty
- isArray
- isObject
- isFunction
- isNumber
- isInteger
- isFloat
- isString
- isDate
- isRegExp
- isFinite
- isNaN
- isBoolean
- isNull
- isScalar
- isTraversable
- isResource
- typeOf
Description: Retrieve all the names of the object's properties.
- object: traversable, the list from which the keys are extracted
_::keys(object)
Table of contents » Object Functions
Description: Return all of the values of the object's properties.
- object: traversable, the list from which the values are extracted
_::values(object)
Table of contents » Object Functions
Description: Convert an object into a list of [key, value] pairs.
- object: traversable, the list of items to convert to pairs
_::pairs(object)
Table of contents » Object Functions
Description: Returns a copy of the object where the keys have become the values and the values the keys. For this to work, all of your object's values should be unique and string serializable.
- object: traversable, the object to invert
_::invert(object)
Table of contents » Object Functions
Alias: methods
Description: Returns a sorted list of the names of every method in an object — that is to say, the name of every function property of the object.
- object: traversable,object, the object to extract the functions from
_::functions(object)
Table of contents » Object Functions
Description: Copy all of the properties in the source objects over to the destination object, and return the destination object. It's in-order, so the last source will override properties of the same name in previous arguments.
- destination: object,array, the destination object
- sources: object,array, multiple, the source objects
_::extend(destination,sources)
Table of contents » Object Functions
Description: Returns a copy of the object, filtered to only have values for the whitelisted keys (or array of valid keys). If provided object is an object (in the broadest sense), a stdClass instance is returned, otherwise an array is returned.
- object: traversable, the object to pick properties on
- keys: array,scalar, multiple, the keys to pick
_::pick(object,keys)
Table of contents » Object Functions
Description: Return a copy of the object, filtered to omit the blacklisted keys (or array of keys). If provided object is an object (in the broadest sense), a stdClass instance is returned, otherwise an array is returned.
- object: traversable, the object to exclude keys from
- keys: array,scalar, multiple, the keys to omit
_::omit(object,keys)
Table of contents » Object Functions
Description: Fill in null properties in object with values from the defaults objects, and return the object. As soon as the property is filled, further defaults will have no effect.
- object: traversable, the object to fill
- defaults: traversable, multiple, the objects or array that will fill object's missing keys
_::defaults(object,defaults)
Table of contents » Object Functions
Alias: copy
Description: Create a shallow-copied clone of the object. Any nested objects or arrays will be copied by reference, not duplicated. This method is safe to use with arrays.
- object: traversable, the object to clone
_::duplicate(object)
Table of contents » Object Functions
Description: Invokes interceptor with the object, and then returns object. The primary purpose of this method is to "tap into" a method chain, in order to perform operations on intermediate results within the chain.
- object: mixed, the object
- interceptor: callable, the function to call with the object as parameter
_::tap(object,interceptor)
Table of contents » Object Functions
Description: Tells whether the object has a non null value for the given key. Gives priority to array's getters ($obj[$key] priorityze on $obj->$key). 'null' is equivalent to 'undefined'.
- object: object,array, the object
- key: scalar, the key
_::has(object,key)
Table of contents » Object Functions
Description: Returns a function that will itself return the key property of any passed-in object.
- key: string,int, the key or offset to get
_::property(key)
Table of contents » Object Functions
Description: Returns a predicate function that will tell you if a passed in object contains all of the key/value properties present in properties.
- properties: traversable, the properties used by predicate
_::matches(properties)
Table of contents » Object Functions
Description: Get the object's key value. If such keys doesn't exists, the default value is returned. If object is neither Array nor an Object, the object itself is returned.
- object: object,array, the object
- key: scalar, the key
- default: mixed, optional, the default value to return in case the key doesn't exists
_::get(object,key,default)
Table of contents » Object Functions
Description: Set object's key value. If object is neither Array nor an Object, the object itself is returned.
- object: mixed, reference, the object
- key: scalar, the key
- value: mixed, the value to set
_::set(object,key,value)
Table of contents » Object Functions
Description: Tells whether the object is of the given type, or class, or pseudo-type. You may pass several types at once (using an array of types or by passing several types as arguments), Underscore::is will return true if object matchs any of these.
- object: mixed, the object
- types: string, the types to test
_::is(object,types)
Table of contents » Object Functions
Description: Performs an optimized deep comparison between the two objects, to determine if they should be considered equal.
- object: mixed, the first object
- other: mixed, the second object
_::isEqual(object,other)
Table of contents » Object Functions
Description: Returns true if object contains no values (no enumerable own-properties). Works with scalars as well.
- object: mixed, the object
_::isEmpty(object)
Table of contents » Object Functions
Description: Returns true if object is an array or usable like an array. If the optionnal native parameter is set to true, it will only return true if object is a native array.
- object: mixed, the object
- native: bool, optional, if true will no consider instances of ArrayAccess as arrays
_::isArray(object,native)
Table of contents » Object Functions
Description: Returns true if value is an Object.
- object: mixed, the object
_::isObject(object)
Table of contents » Object Functions
Description: Returns true if object is a Function.
- object: mixed, the object
_::isFunction(object)
Table of contents » Object Functions
Alias: isNum, isNumeric
Description: Returns true of object is a Number. If the optionnal native parameter is set to true, it will only return true if object is a native int or float.
- object: mixed, the object to pick properties on
- native: bool, optional, if true will not consider SplType instances as numbers
_::isNumber(object,native)
Table of contents » Object Functions
Alias: isInt
Description: Returns true if the object is an integer. If the optional native parameter is set to true, it will only return true if object is a native int.
- object: mixed, the object
- native: bool, optional, if true will not consider instances of SplInt as integers
_::isInteger(object,native)
Table of contents » Object Functions
Description: Returns true if the object is a float. If the optional native parameter is set to true, it will only return true if object is a native float.
- object: mixed, the object
- native: bool, optional, if true will not consider instances of SplFloat as integers
_::isFloat(object,native)
Table of contents » Object Functions
Description: Returns true if object is a String. If object is an object with a __toString method, it will be considered as a string as well. If the optionnal native parameter is set to true, it will only return true if object is a native string.
- object: mixed, the object
- native: bool, optional, if true will not consider object with toString or SplString as strings
_::isString(object,native)
Table of contents » Object Functions
Description: Returns true if object is a DateTime instance. Everything the strtotime function can understand is also considered a date.
- object: mixed, the object
_::isDate(object)
Table of contents » Object Functions
Description: Returns true if object is a valid regular expression (PCRE).
- object: mixed, the object
_::isRegExp(object)
Table of contents » Object Functions
Description: Returns true if object is a finite number.
- object: mixed, the object
_::isFinite(object)
Table of contents » Object Functions
Description: Returns true if object is NaN (Not a Number).
- object: mixed, the object
_::isNaN(object)
Table of contents » Object Functions
Alias: isBool
Description: Returns true if object is a Boolean. If the optionnal native parameter is set to true, it will only return true if object is a native boolean.
- object: mixed, the object
- native: bool, optional, if true will not consider instances of SplBool as integers
_::isBoolean(object,native)
Table of contents » Object Functions
Description: Returns true if object is Null.
- object: mixed, the object
_::isNull(object)
Table of contents » Object Functions
Description: Returns true if $object is a scalar. If the optionnal native parameter is set to true, it will only return true if object is a native scalar.
- object: mixed, the object
- native: mixed, no description available...
_::isScalar(object,native)
Table of contents » Object Functions
Description: Returns true if the object can be traversed with a foreach loop.
- object: mixed, the object
_::isTraversable(object)
Table of contents » Object Functions
Description: Returns true if the object is a resource (like a file handle returned by fopen).
- object: mixed, the object
_::isResource(object)
Table of contents » Object Functions
Alias: getType
Description: Gets the class of given object or its native type. This function aggregates most of the is* functions and can be seen as a more preceise version of PHP native function gettype. The class parameters lets you know the exact type of the object, if set to false 'object' is returned for objects. Otherwise will return one of the Underscore::TYPE_* constants.
- object: mixed, the object
- class: bool, optional, if true will return the exact class of $object instead of TYPE_OBJECT
_::typeOf(object,class)
Table of contents » Object Functions
Description: Returns the same value that is used as the argument. In math: f(x) = x. This function looks useless, but is used throughout Underscore as a default iterator.
- value: mixed, the value to return
_::identity(value)
Table of contents » Utility Functions
Description: Creates a function that returns the same value that is used as the argument of _::constant.
- value: mixed, the value
_::constant(value)
Table of contents » Utility Functions
Description: Returns undefined irrespective of the arguments passed to it. Useful as the default for optional callback arguments.
_::noop()
Table of contents » Utility Functions
Description: Invokes the given iterator function n times. Each invocation of iterator is called with an index argument. Produces an array of the returned values.
- n: int, the number of time $iterator will be run
- iterator: callable, the iterator function
- context: object, optional, if provided will become the context for $iterator
_::times(n,iterator,context)
Table of contents » Utility Functions
Description: Returns a random integer between min and max, inclusive. If you only pass one argument, it will return a number between 0 and that number.
- min: int, the lower bound (or the max if $max is null, the min being 0 then)
- max: int, optional the upper bound
_::random(min,max)
Table of contents » Utility Functions
Description: Allows you to extend Underscore with your own utility functions. Pass a hash of array('name' => function) definitions to have your functions added to the Underscore library, as well as the OOP wrapper.
- functions: array, an collection of functions to add to the Underscore class
_::mixin(functions)
Table of contents » Utility Functions
Description: Returns callable version of any Underscore method (event the user defined ones).
- method: string, multiple, the Underscore's method name(s)
_::provide(method)
Table of contents » Utility Functions
Description: Generate a pseudo-unique id.
- prefix: string, optional, a prefix for the id
_::uniqueId(prefix)
Table of contents » Utility Functions
Description: Escapes a string for insertion into HTML, replacing &, <, >, ", ', and / characters.
- string: string, the string to escape
_::escape(string)
Table of contents » Utility Functions
Description: The opposite of escape, replaces &, <, >, ", ', and / with their unescaped counterparts.
- string: string, the string to unescape
_::unescape(string)
Table of contents » Utility Functions
Description: If the value of the named property is a function then invoke it with the object as context; otherwise, return it.
- object: object,array, the object or array
- property: scalar, the property to get
_::result(object,property)
Table of contents » Utility Functions
Description: The equivalent of the finally keywork (available since PHP 5.5).
- function: callable, a function
- finally: callable, another function that will always be executed after $function
- context: object, the functions context
_::lastly(function,finally,context)
Table of contents » Utility Functions
Description: Compiles PHP templates into functions that can be evaluated for rendering. Useful for rendering complicated bits of HTML from JSON data sources. Template functions can both interpolate variables, using <%= ... %>, as well as execute arbitrary PHP code, with <% ... %>. If you wish to interpolate a value, and have it be HTML-escaped, use <%- ... %> When you evaluate a template function, pass in a data object that has properties corresponding to the template's free variables. If you're writing a one-off, you can pass the data object as the second parameter to template in order to render immediately instead of returning a template function. The settings argument should be a hash containing any Underscore::$templateSettings that should be overridden. If ERB-style delimiters aren't your cup of tea, you can change Underscore's template settings to use different symbols to set off interpolated code. Define an interpolate regex to match expressions that should be interpolated verbatim, an escape regex to match expressions that should be inserted after being HTML escaped, and an evaluate regex to match expressions that should be evaluated without insertion into the resulting string. You may define or omit any combination of the three.
- templateString: string, the template buffer
- data: array,object, optional, if provided will compute the template using this array as variables
- settings: array, optional, il provided will override default matchers (use with care)
_::template(templateString,data,settings)
Table of contents » Utility Functions
Description: Returns a wrapped object. Calling methods on this object will continue to return wrapped objects until value is used. Calling chain will cause all future method calls to return wrapped objects. When you've finished the computation, use value to retrieve the final value.
- object: mixed, the chaining initial state
_::chain(object)
Alias: strategy
Description: Create new mixins on runtime. The implementation is based on Bob Weinand's idea of Scala traits implementation in PHP (see it here https://gist.github.com/bwoebi/7319798). This method decomposes the $classname to create a new class, using '\with' as a separator for traits.
- classname: string, the class to forge
_::forge(classname)