Streams
, (*1)
Streams is a port of the Streams library for PHP. It makes working with
collections super pleasant., (*2)
Installation
Just add the following to your composer.json
file:, (*3)
"pepegar/streams-php": "dev-master"
Usage
An example with the Yii ActiveRecord lib:, (*4)
<?php
use Streams as S;
$collection = Car::model()->findAll(); // Returns an array of Car objects
$carStream = new S\Stream($collection);
$newCollection = $carStream
->filter(function( $car ) {
return ($car->price > 36000); // return only expensive cars!
})->map(function( $car ) {
$car->setCo2EmissionTaxes(20); // Since is an expensive car, lets make the people who drive it more poor :D
return $car;
})->getElements();
Available functions
Even though this library is under active development, the currently available
methods are:, (*5)
map(callable $callback)
As in every functional programming language, map takes a function as argument
and applies it to each element in the array, returning a new array with the
results., (*6)
filter(callable $callback)
takes a function as argument and applies it to each element in the collection.
It returns a new collection containing all elements where the callback returned
true., (*7)
allMatch(callable $predicate)
returns wether all the elements in the stream match the given predicate, (*8)
anyMatch(callable $predicate)
returns wether any the elements in the stream match the given predicate, (*9)
concat(Stream $a, Stream $b)
Creates a lazily concatenated stream whose elements are all the elements of the
first stream followed by all the elements of the second stream., (*10)
count()
returns the count of elements in the stream, (*11)
distinct()
returns a new stream consisting of the distinct elements of the stream, (*12)
Hacking
Please, submit your Pull Requests, and make sure that the build passes., (*13)