n11t / abstract-collection
Abstract collection to handle object lists
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: 2025-06-06 00:27:43 UTC
README
AbstractCollection
The AbstractCollection can be used to created typed lists.
Why?
With php7 the language improved a lot. But it's still not possible to use generics or typed arrays as parameter or return value. So we have to use a workaround.
With this abstract class you are able to build your own typed collection.
Usage
Extend from the AbstractCollection class and override the constructor.
class ProductCollection extends \N11t\AbstractCollection\AbstractCollection {
public function __construct(Product ...$products)
{
$this->values = $products;
}
}
Now you can type hint a collection of products everywhere in your code and be sure you get one.
Sampe Code
<?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());
Output
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)
}