pogulailo / collection
严格类型集合
v1.0.0
2022-09-13 05:43 UTC
Requires (Dev)
- phpunit/phpunit: ^9.5
This package is auto-updated.
Last update: 2024-09-12 22:51:32 UTC
README
PHP中严格类型数组的一个简单简洁实现。没有额外代码,只有类型检查数组。
用法
首先你需要创建自己的集合类,该类继承自 GenericCollection
并设置其类型
use Pogulailo\Collection\GenericCollection; class CustomerCollection extends GenericCollection { public function __construct(...$values) { parent::__construct(Customer::class, ...$values); } }
这就完了,然后你就可以享受到严格类型数组的所有优点
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);
你也可以选择不创建自己的集合类,但这样你可能需要做额外的类型检查
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);