Collections — How to improve your PHP code

Andrew Pogulailo
3 min readSep 13, 2022

--

Photo by Kin Li

Quite often, we need to process a group of objects of the same type, and you can often see that an ordinary array is used for this. But there are several significant problems with this approach that are solved by using Сollections. A сollection is an array in which only elements of the same type can be stored. Let’s consider the problems that arise when using arrays in the example of the following code, which simply sends notifications to a group of clients.

This code will work and send notifications, but it has a couple of major problems, the array can contain absolutely anything, and we don’t validate its contents. Therefore, the following problem may arise in the future:

Sooner or later, there will be data in the array that should not be there, the result can be unpredictable, so we need to add a check of the contents of the array. This is just an example, in the end, it will not be enough to sleep peacefully on Friday night.

Problem solved, but I don’t like checking the contents of an array every time, so let’s finally ditch the regular array and use a Сollection instead. Let’s add the Collection library to the project.

composer require pogulailo/collection

It looks much better, now we can be sure that all elements of the collection are of the same type, and work with them. But this is also not enough, because you can easily change the type of Сollection.

Therefore, we still need to check the type of Сollection. It’s already much better, at least we do it once, and not during every iteration.

But there is a better and more straightforward solution to this problem, we can use a specific collection for each data type. It may sound complicated, but the pros of this approach far outweigh the cons. And you won’t have to write a lot of code.

This is all we need to create a new type of collection.

Now we can be sure that only elements of a specific type are in our collection. It is very convenient to use in Interfaces, and in general, it is much more convenient than a regular array or GenericCollection.

I think this approach will help simplify and improve your code. While we are all waiting for the appearance of Generics in PHP.

--

--

Andrew Pogulailo

I specialize in developing high-load systems. I'm passionate about using my skills to create innovative web solutions that drive business success.