n11t / 抽象集合
用于处理对象列表的抽象集合
1.2.0
2018-03-28 14:21 UTC
Requires (Dev)
- phpunit/phpunit: >=6.5 <7.0.0
This package is not auto-updated.
Last update: 2024-09-26 21:21:05 UTC
README
AbstractCollection
AbstractCollection 可以用来创建类型化的列表。
为什么?
随着 php7 的推出,语言有了很大的改进。但仍然无法使用泛型或类型化数组作为参数或返回值。因此,我们需要使用一个变通方法。
使用这个抽象类,你可以构建自己的类型化集合。
使用方法
从 AbstractCollection 类扩展并重写构造函数。
class ProductCollection extends \N11t\AbstractCollection\AbstractCollection {
public function __construct(Product ...$products)
{
$this->values = $products;
}
}
现在你可以在代码中的任何地方对产品集合进行类型提示,并确保你得到一个。
示例代码
<?php
declare(strict_types=1);
require_once __DIR__ . '/vendor/autoload.php';
// Extend from AbstractCollection
class IntCollection extends \N11t\AbstractCollection\AbstractCollection {
public function __construct(int ...$values)
{
$this->values = $values;
}
}
// Type hint for collections instead of array
function write_ln(string $context, IntCollection $collection) {
echo $context . PHP_EOL;
// Iterate over
foreach ($collection as $item) {
echo $item . PHP_EOL;
}
}
// Initialize typed collection.
$integer = [1,2,3,4,5];
$collection = new IntCollection(...$integer);
// Count collection
echo 'Collection count: ' . \count($collection) . PHP_EOL;
// Sort collection
write_ln('pre sort', $collection);
$collection->usort(function (int $a, int $b) {
return $b <=> $a;
});
write_ln('post sort', $collection);
// Filter collection
$filteredCollection = $collection->filter(function(int $value, $key) {
return $value % 2 === 0 || $key === 0;
}, \ARRAY_FILTER_USE_BOTH);
// Use toArray to get values
var_dump($collection->toArray());
输出
Collection count: 5
pre sort
1 2 3 4 5
post sort
5 4 3 2 1
array(3) {
[0]=>
int(5)
[1]=>
int(4)
[3]=>
int(2)
}