In this article we will see how to define a custom PHP collection
An Array is a basic data structure that stores values key/value without any constrictions or any OOP method and it is very difficult to control and maintain the data they contain.
But if we want to decouple from the framework or we use another framework and do not want to install the dependency we can create our own collection.
In this article, we will see how to build our own collection with some methods to work with objects. In the example, it is focused on a CQRS architecture and we place the collection in the reading layer.
NOTE:In the code examples we have used PHP 8.1 but the code is fully adaptable to any other version.
Custom collection:
Firstly create a custom collection without type validation and add some callable functions fromMap, reduce, map, each, some, filter and other OOP functions like first, last, count, isEmpty, add, values, items, getIterator . This is the base of OOP wrapper for working with arrays.
src/Shared/Domain/Read/Collection.php
Custom typed Collection:
The typed collection extends the above collection and implements the constraints.
NOTE:To avoid creating more code than necessary I have used the webmozzart/assert (pakagist) library but feel free to implement your validations.
src/Shared/Domain/Read/TypedCollection.php
Example implement Typed Collection:
First of all, we need a create a basic Entity Class, in this case create a simple class called Foo.
Then can create a typed collection that contain a Foo inside