Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of creating collection classes in PHP?

I've been reading Alejandro Gervasio's excellent Service Layers series here: http://www.devshed.com/cp/bio/Alejandro-Gervasio/ and I noticed he is also one of the developers who favors PHP Collections, as in http://www.devshed.com/c/a/PHP/PHP-Service-Layers-Handling-Entity-Collections/1/

Why is that? Why create a class that simulates a simple associative array by using arrays in itself?

like image 839
Swader Avatar asked Apr 08 '12 21:04

Swader


1 Answers

I didnt read the article but i can tell you why i do it generally speaking:

  1. Searching/Sorting/Accessing: I can abstract searching, filtering, and accessing the items i want in the collection without going to the db with special methods and without being dependent on a single array key.
  2. Its easier to plugin to an entity management interface if you can pass in and Entity or an EntityCollection interface - again here you can have functionality encapsulated in the collection for performing operations on multiple entities. Not that you cant just do this in a loop, but it lets you hide it away and make specific things happen for different collection classes).
  3. Collection serialization - custom serialization (think picking specific attributes) for serialization to a specific string format.
  4. You can still support an array interface for basic access and iteration easily.
like image 154
prodigitalson Avatar answered Sep 28 '22 10:09

prodigitalson