pogulailo / collection
Strictly typed collection
Installs: 15
Dependents: 0
Suggesters: 0
Security: 0
Stars: 4
Watchers: 2
Forks: 0
Open Issues: 0
pkg:composer/pogulailo/collection
Requires (Dev)
- phpunit/phpunit: ^9.5
This package is auto-updated.
Last update: 2025-09-13 00:48:46 UTC
README
A simple and concise implementation of strictly typed arrays in PHP. No extra code, just type-checked arrays.
Usage
First you need to create your own collection class which extends the GenericCollection
and sets its type:
use Pogulailo\Collection\GenericCollection; class CustomerCollection extends GenericCollection { public function __construct(...$values) { parent::__construct(Customer::class, ...$values); } }
That's all, then you can enjoy all the advantages of strictly typed arrays:
function getCustomers(): CustomerCollection { $customers = new CustomerCollection(); $customers->append(new Customer()); $customers->append(new Customer()); $customers->append(new Customer()); return $customers; } function doSomething(CustomerCollection $customers): void { foreach ($customers as $customer) { // Do what you need to do } } $customers = getCustomers(); doSomething($customers);
You can choose not to create your own collection class, but then you will need to do additional type checking:
use Pogulailo\Collection\GenericCollection; function getCustomers(): GenericCollection { $customers = new GenericCollection(Customer::class); $customers->append(new Customer()); $customers->append(new Customer()); $customers->append(new Customer()); return $customers; } function doSomething(GenericCollection $customers): void { // In this case, you need to check the collection type first if ($customers->getType() !== Customer::class) { throw new Exception('I need customers, more customers...') } foreach ($customers as $customer) { // Do what you need to do } } $customers = getCustomers(); doSomething($customers);