百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
K

Knapsack

> 包管理
开源

用于 PHP 的集合管道库

534 stars0 点赞3 次浏览
访问官网GitHub

工具介绍

用于 PHP 的集合管道库

Knapsack

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.

Documentation

Check out the documentation (which is prettified version of this readme) at http://dusankasan.github.io/Knapsack

Installation

Require this package using Composer.

composer require dusank/knapsack

Usage

Instantiate via static or dynamic constructor

php
use 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.

Work with arrays, Traversable objects or callables that produce Traversables

php
$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;
    }
});

Basic map/reduce

php
$result = Collection::from([1, 2])
    ->map(function($v) {return $v*2;})
    ->reduce(function($tmp, $v) {return $tmp+$v;}, 0);
    
echo $result; //6

The same map/reduce using Knapsack's collection functions

php
$result = reduce(
    map(
        [1, 2], 
        function($v) {return $v*2;}
    ),
    function($tmp, $v) {return $tmp+$v;},
    0
);

echo $result; //6

Get first 5 items of Fibonacci's sequence

php
$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

If array or Traversable would be returned from functions that return an item from the collection, it can be converted to Collection using the optional flag. By default it returns the item as is.

php
$result = Collection::from([[[1]]])
    ->first(true)
    ->first();
    
var_dump($result); //[1]

Collections are immutable

php
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; //9

Keys are not unique by design

It would harm performance. This is only a problem if you need to call toArray(), then you should call values() before.

php
$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:4

Collection trait is provided

If 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.

php
class AwesomeIterator extends ArrayIterator {
    use CollectionTrait;
}

$iterator = new AwesomeIterator([1, 2, 3]);
$iterator->size(); //3

Performance tests

PHP 5.6

…

PHP 7.1.1

…

Constructors

These are ways how to create the Collection class. There is one default constructor and few named (static) ones.

new(iterable|callable $input)

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.

php
$collection = new Collection([1, 2, 3]);
php
$collection = new Collection(new ArrayIterator([1, 2, 3]));
php
$generatorFactory = function () {
    foreach ([1, 2] as $value) {
        yield $value;
    }
};

$collection = new Collection($generatorFactory);

from(iterable|callable $input)

Collection::from is a static alias of the default constructor. This is the preferred way to create a Collection.

php
$collection = Collection::from([1, 2, 3]);
php
$collection = Collection::from(new ArrayIterator([1, 2, 3]));
php
$generatorFactory = function () {
    foreach ([1, 2] as $value) {
        yield $value;
    }
};

$collection = Collection::from($generatorFactory);

iterate(mixed $input, callable $function)

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.

php
$collection = Collection::iterate(1, function ($value) {return $value + 1;}); // 1, 2, 3, 4 ...

repeat(mixed $value, int $times = -1)

Returns a lazy collection of $value repeated $times times. If $times is not provided the collection is infinite.

php
Collection::repeat(1); //infinite collection of ones
php
Collection::repeat(1, 4)->toArray(); //[1, 1, 1, 1]

range(int $start = 0, int $end = null, int step = 1)

Returns a lazy collection of numbers starting at $start, incremented by $step until $end is reached.

php
Collection::range(0, 6, 2)->toArray(); //[0, 2, 4, 6]

Operations

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).

Standard Iterator methods

It implements http://php.net/manual/en/class.iterator.php

append(mixed $item, mixed $key = null) : Collection

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.

php
Collection::from([1, 3, 3, 2])
    ->append(1)
    ->toArray(); //[1, 3, 3, 2, 1]
php
Collection::from([1, 3, 3, 2])
    ->append(1, 'key')
    ->toArray(); //[1, 3, 3, 2, 'key' => 1]
php
toArray(append([1, 3, 3, 2], 1, 'key')); //[1, 3, 3, 2, 'key' => 1]

average() : int|float

Returns average of values in this collection.

php
Collection::from([1, 2, 3, 2])->average(); //2
Collection::from([1, 2, 3, 2, 2])->average(); //2.2
Collection::from([])->average(); //0
php
average([1, 2, 3]); //2

combine(iterable $collection, bool $strict = false) : Collection

Combines 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.

php
Collection::from(['a', 'b'])
    ->combine([1, 2])
    ->toArray(); //['a' => 1, 'b' => 2]
php
toArray(combine(['a', 'b'], [1, 2])); //['a' => 1, 'b' => 2]

concat(iterable ...$collections) : Collection

Returns a lazy collection with items from this collection followed by items from the collection from first argument, then second and so on.

php
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]
php
toArray(values(concat([1, 3, 3, 2], [4, 5]))); //[1, 3, 3, 2, 4, 5]  

contains(mixed $needle) : bool

Returns true if $needle is present in the collection.

php
Collection::from([1, 3, 3, 2])->contains(2); //true
php
contains([1, 3, 3, 2], 2); //true

countBy(callable $function) : Collection

Returns 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.

php
Collection::from([1, 2, 3, 4, 5])
    ->countBy(function ($value) {
        return $value % 2 == 0 ? 'even' : 'odd';
    })
    ->toArray(); //['odd' => 3, 'even' => 2]  
php
toArray(countBy([1, 2, 3, 4, 5], function ($value) {return $value % 2 == 0 ? 'even' : 'odd';}));      

cycle() : Collection

Returns an infinite lazy collection of items in this collection repeated infinitely.

php
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]
php
toArray(values(take(cycle([1, 3, 3, 2]), 8))); //[1, 3, 3, 2, 1, 3, 3, 2]

diff(iterable ...$collections) : Collection

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· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

PHPcollectioncollection-pipelinecollectionslazy-collections

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类包管理
定价开源

> 相关工具

N
npm
Node.js 默认包管理器
P
pnpm
高效节省磁盘的 Node 包管理器
I
is-gif
Check if a Buffer/Uint8Array is a GIF image