用于 PHP 的集合管道库
Collection pipeline library for PHP
Knapsack is a collection library for PHP >= 5.6 that implements most of the sequence operations proposed by Clojures sequences plus some additional ones. All its features are available as functions (for functional programming) and as a collection pipeline object methods.
The heart of Knapsack is its Collection class. However its every method calls a simple function with the same name that does the actual heavy lifting. These are located in DusanKasan\Knapsack namespace and you can find them here. Collection is a Traversable implementor (via IteratorAggregate) that accepts Traversable object, array or even a callable that produces a Traversable object or array as constructor argument. It provides most of Clojures sequence functionality plus some extra features. It is also immutable - operations preformed on the collection will return new collection (or value) instead of modifying the original collection.
Most of the methods of Collection return lazy collections (such as filter/map/etc.). However, some return non-lazy collections (reverse) or simple values (count). For these operations all of the items in the collection must be iterated over (and realized). There are also operations (drop) that iterate over some items of the collection but do not affect/return them in the result. This behaviour as well as laziness is noted for each of the operations.
If you want more example usage beyond what is provided here, check the specs and/or scenarios. There are also performance tests you can run on your machine and see the computation time impact of this library (the output of these is included below).
Feel free to report any issues you find. I will do my best to fix them as soon as possible, but community pull requests to fix them are more than welcome.
Check out the documentation (which is prettified version of this readme) at http://dusankasan.github.io/Knapsack
Require this package using Composer.
composer require dusank/knapsackuse DusanKasan\Knapsack\Collection;
$collection1 = new Collection([1, 2, 3]);
$collection2 = Collection::from([1, 2, 3]); //preferred since you can call methods on its result directly.$collection1 = Collection::from([1, 2, 3]);
$collection2 = Collection::from(new ArrayIterator([1, 2, 3]);
//Used because Generator can not be rewound
$collection2 = Collection::from(function() { //must have 0 arguments
foreach ([1, 2, 3] as $value) {
yield $value;
}
});$result = Collection::from([1, 2])
->map(function($v) {return $v*2;})
->reduce(function($tmp, $v) {return $tmp+$v;}, 0);
echo $result; //6$result = reduce(
map(
[1, 2],
function($v) {return $v*2;}
),
function($tmp, $v) {return $tmp+$v;},
0
);
echo $result; //6$result = Collection::iterate([1,1], function($v) {
return [$v[1], $v[0] + $v[1]]; //[1, 2], [2, 3] ...
})
->map('\DusanKasan\Knapsack\first') //one of the collection functions
->take(5);
foreach ($result as $item) {
echo $item . PHP_EOL;
}
//1
//1
//2
//3
//5$result = Collection::from([[[1]]])
->first(true)
->first();
var_dump($result); //[1]function multiplyBy2($v)
{
return $v * 2;
}
function multiplyBy3($v)
{
return $v * 3;
}
function add($a, $b)
{
return $a + $b;
}
$collection = Collection::from([1, 2]);
$result = $collection
->map('multiplyBy2')
->reduce(0, 'add');
echo $result; //6
//On the same collection
$differentResult = $collection
->map('multiplyBy3')
->reduce(0, 'add');
echo $differentResult; //9It would harm performance. This is only a problem if you need to call toArray(), then you should call values() before.
$result = Collection::from([1, 2])->concat([3,4]);
//arrays have unique keys
$result->toArray(); //[3,4]
$result->values()->toArray(); //[1, 2, 3, 4]
//When iterating, you can have multiple keys.
foreach ($result as $key => $item) {
echo $key . ':' . $item . PHP_EOL;
}
//0:1
//1:2
//0:3
//1:4If you wish to use all the Collection methods in your existing classes directly, no need to proxy their calls, you can just use the provided CollectionTrait. This will work on any Traversable by default. In any other class you will have to override the getItems() method provided by the trait. Keep in mind that after calling filter or any other method that returns collection, the returned type will be actually Collection, not the original Traversable.
class AwesomeIterator extends ArrayIterator {
use CollectionTrait;
}
$iterator = new AwesomeIterator([1, 2, 3]);
$iterator->size(); //3……These are ways how to create the Collection class. There is one default constructor and few named (static) ones.
The default constructor accepts array, Traversable or a callable that takes no arguments and produces Traversable or array. The use case for the callable argument is for example a Generator, which can not be rewound so the Collection must be able to reconstruct it when rewinding itself.
$collection = new Collection([1, 2, 3]);$collection = new Collection(new ArrayIterator([1, 2, 3]));$generatorFactory = function () {
foreach ([1, 2] as $value) {
yield $value;
}
};
$collection = new Collection($generatorFactory);Collection::from is a static alias of the default constructor. This is the preferred way to create a Collection.
$collection = Collection::from([1, 2, 3]);$collection = Collection::from(new ArrayIterator([1, 2, 3]));$generatorFactory = function () {
foreach ([1, 2] as $value) {
yield $value;
}
};
$collection = Collection::from($generatorFactory);Returns lazy collection of values, where first value is $input and all subsequent values are computed by applying $function to the last value in the collection. By default this produces an infinite collection. However you can end the collection by throwing a NoMoreItems exception.
$collection = Collection::iterate(1, function ($value) {return $value + 1;}); // 1, 2, 3, 4 ...Returns a lazy collection of $value repeated $times times. If $times is not provided the collection is infinite.
Collection::repeat(1); //infinite collection of onesCollection::repeat(1, 4)->toArray(); //[1, 1, 1, 1]Returns a lazy collection of numbers starting at $start, incremented by $step until $end is reached.
Collection::range(0, 6, 2)->toArray(); //[0, 2, 4, 6]These are the operations (methods) provided by Collection class. For each one, there is a function with the same name in Knapsack namespace. The function has the same footprint as the method, except it has one extra argument prepended - the collection (array or Traversable).
It implements http://php.net/manual/en/class.iterator.php
Returns a lazy collection of items of this collection with $item added as last element. If $key is not provided, its key will be the next integer in the sequence.
Collection::from([1, 3, 3, 2])
->append(1)
->toArray(); //[1, 3, 3, 2, 1]Collection::from([1, 3, 3, 2])
->append(1, 'key')
->toArray(); //[1, 3, 3, 2, 'key' => 1]toArray(append([1, 3, 3, 2], 1, 'key')); //[1, 3, 3, 2, 'key' => 1]Returns average of values in this collection.
Collection::from([1, 2, 3, 2])->average(); //2
Collection::from([1, 2, 3, 2, 2])->average(); //2.2
Collection::from([])->average(); //0average([1, 2, 3]); //2Combines the values of this collection as keys, with values of $collection as values. The resulting collection has length equal to the size of smaller collection. If $strict is true, the size of both collections must be equal, otherwise ItemNotFound is thrown. When strict, the collection is realized immediately.
Collection::from(['a', 'b'])
->combine([1, 2])
->toArray(); //['a' => 1, 'b' => 2]toArray(combine(['a', 'b'], [1, 2])); //['a' => 1, 'b' => 2]Returns a lazy collection with items from this collection followed by items from the collection from first argument, then second and so on.
Collection::from([1, 3, 3, 2])
->concat([4, 5]) //If we would convert to array here, we would loose 2 items because of same keys [4, 5, 3, 2]
->values()
->toArray(); //[1, 3, 3, 2, 4, 5]toArray(values(concat([1, 3, 3, 2], [4, 5]))); //[1, 3, 3, 2, 4, 5] Returns true if $needle is present in the collection.
Collection::from([1, 3, 3, 2])->contains(2); //truecontains([1, 3, 3, 2], 2); //trueReturns a collection of items whose keys are the return values of $function(value, key) and values are the number of items in this collection for which the $function returned this value.
Collection::from([1, 2, 3, 4, 5])
->countBy(function ($value) {
return $value % 2 == 0 ? 'even' : 'odd';
})
->toArray(); //['odd' => 3, 'even' => 2] toArray(countBy([1, 2, 3, 4, 5], function ($value) {return $value % 2 == 0 ? 'even' : 'odd';})); Returns an infinite lazy collection of items in this collection repeated infinitely.
Collection::from([1, 3, 3, 2])
->cycle()
->take(8) //we take just 8 items, since this collection is infinite
->values()
->toArray(); //[1, 3, 3, 2, 1, 3, 3, 2]toArray(values(take(cycle([1, 3, 3, 2]), 8))); //[1, 3, 3, 2, 1, 3, 3, 2]Returns a lazy collection of items that are in $collection but are not in any of the other arguments, indexed by the keys from the first collection. N
暂无开放 Issues,或尚未同步最近议题。