一個為 PHP 提供一組簡約、類型化和管道式不可變集合的函式庫。
PHP > 7.2
composer require dcsg/php-immutable-collections
PHP 中缺少泛型,因此不允許在 PHP 中使用類型化集合。
該庫提供了兩個抽象的不可變集合:
由於 PHP 不像 Java 那樣具有泛型,因此不可能有本機型別集合。該庫中提供的集合是您創建自己的類型化集合的基礎,您只需擴展它們即可。
DDD 就是讓您的程式碼使用商業語言,也就是所謂的「無所不在的語言」。如果沒有 PHP 中的集合,使用Arrays
就很難實現這一點,因為您無法為它們添加行為。因此,通常會發生的情況是,您將該行為添加到您的實體中,但它不應該在那裡。另一個問題是Arrays
的可變性, VOs
(值物件)必須始終是不可變的,這對於Arrays
來說是不可能的,並且您應該始終保證該Array
的elements
都是相同的類型。
Collections
和Arrays
都表示一組元素。Collections
,而Arrays
則支援。Arrays
是 PHP 的資料結構,幾乎用於所有用途。Arrays
不允許添加新行為,而Collections
允許。Arrays
不允許為其元素定義類型,而Collections
允許。 還有其他 PHP 集合,其中包括 Doctrine Collections 和 Illuminate Collections。這些集合解決了不同的問題,針對其特定用例進行了定制,並且它們的 API 非常廣泛,更重要的是,這些集合是可變的。這些組合使得很難將這些集合用於更簡單的用例。這就是為什麼我們在這裡提供的 Collections 具有非常小的 API,甚至不公開 Iterator API。這樣您就可以使用它們並根據您的需求擴展其行為。
isEmpty
、 count
、 toArray
、 contains
、 get
、 map
、 filter
、 slice
、 merge
、 reverse
、 reduce
、 first
、 last
、 head
、 tail
。 <?php declare (strict_types= 1 );
use DCSG ImmutableCollections ImmutableCollection ;
final class MyStringCollection extends ImmutableCollection {
protected function validateItems ( array $ elements ): void
{
foreach ( $ elements as $ element ) {
if (! is_string ( $ element )) {
throw new InvalidArgumentException ( ' Element is not a String. ' );
}
}
}
}
$ collection = MyStringCollection:: create ([ ' foo ' , ' bar ' ]);
echo $ collection -> count (); // 2
$ slicedCollection = $ collection -> slice ( 0 , 1 ); // MyStringCollection { $elements=['foo']}
<?php declare (strict_types= 1 );
use DCSG ImmutableCollections SetImmutableCollection ;
final class MyStringSetCollection extends SetImmutableCollection {
protected function validateItems ( array $ elements ): void
{
foreach ( $ elements as $ element ) {
if (! is_string ( $ element )) {
throw new InvalidArgumentException ( ' Element is not a String. ' );
}
}
}
}
$ collection = MyStringSetCollection:: create ([ ' foo ' , ' bar ' ]);
echo $ collection -> count (); // 2
$ slicedCollection = $ collection -> tail (); // MyStringSetCollection { $elements=['bar']}
$ collection = MyStringSetCollection:: create ([ ' foo ' , ' bar ' , ' foo ' ]); // Throws InvalidArgumentException
我們提供兩個簡單的例子來更好地理解。其中一項與發票有關,另一項與貨船的腿有關。
請參閱變更日誌以了解有關最近更改內容的更多資訊。
$ composer test
有關詳細信息,請參閱貢獻和行為準則。
如果您發現任何與安全相關的問題,請發送電子郵件至 [email protected],而不是使用問題追蹤器。
麻省理工學院許可證 (MIT)。請參閱許可證文件以獲取更多資訊。