Question

I'm learning PHP5 (last time I checked PHP was in PHP4 days) and I'm glad to see that PHP5 OO is more Java-alike than the PHP4 one but there's still an issue that makes me feel quite unconfortable because of my Java background : ARRAYS.

I'm reading "Proffesional PHP6" (Wrox) and It shows its own Collection implementation. I've found other clases like the one in http://aheimlich.dreamhosters.com/generic-collections/Collection.phps based on SPL. I've also found that there's some kind of Collection in SPL (ArrayObject)

However, I'm surprised because I don't really see people using Collections in PHP, they seem to prefer arrays.

So, isn't it a good idea using Collections in PHP just like people use ArrayList instead of basic arrays in Java? After all, php arrays aren't really like java arrays.

Was it helpful?

Solution

Collections in Java make a lot of sense since it's a strongly typed language. It makes sense to have a collection of say "Cars" and another of "Motorbikes".

However, in PHP, due to the dynamically typed nature, it is quite common to sacrifice the formality of Collections. Arrays are sufficient to be used as generic containers of various object types (Cars, Motorbikes, etc.). Also, the added benefit comes from the fact that arrays can be mutated very easily (which sometimes can be a big disadvantage when proper error checking is absent).

I come from a Java background, and I've found that using a Collections design pattern in PHP does not buy much in the way of advantages (no multi-threading, no optimization of memory allocation, no iterators, etc.).

If you're looking for any of those advantages, its probably better to construct a wrapper class around the array, implementing each feature (iterators, etc.) a la carte.

OTHER TIPS

I am very pro collection objects in PHP, they can be used to add type safety, impliment easy to use search, sort and manipulation functionality, and represent the correct OO approach rather then using arrays and the multitude of useful but procedual functions that operate on them in differing patterns all over the source.

We have various collections that we use for various purposes all neatly inherited promoting type safety, consistent coding standards and a high level of code reuse.

But ultimatley, they are all array's internally!

I suppose really it comes down to choice, but in my object oriented world I like to keep easily repeatable segments of code such as sort and search algorithms in base classes, and I find the object notation more self documenting.

PHP arrays are associative... They're far more powerful than Java's arrays, and include much of the functionality of List<> and Map<>.

What do you mean by "good idea"? They're different tools, using one language in the way you used another usually results in frustration.

I, too, was somewhat dismayed to find no Collection type classes in PHP. Arrays have a couple of real disadvantages in my experience.

First, the number of functions available to manipulate them is somewhat limited. For example, I need to be able to arbitrarily insert and remove items to/from a Collection at a given index position. Doing that with the built-in language functions for arrays in PHP is painful at best.

Second, as a sort of offshoot of the first point, writing clean, readable code that manipulates arrays at any level of complexity beyond simple push/pop and iterator stuff is difficult at best. I often find that I have to use one array to index and keep track of another array in data-intensive apps I create.

I prefer working in a framework (my personal choice is NOLOH). There, I have a real Collection class called ArrayList that has functions such as Add, Insert, RemoveAt, RemoveRange and Toggle. I imagine other PHP frameworks address this issue as well.

A nice implementation of collection in php is provided by Varien Lib, this library is part of Magento code with OSL license. ( more info about Magento license and code reuse here.

Cannot find any source code for the library so the best way is to download magento and then look in /lib/Varien/

Yii has implementation of full java like collections stack

http://www.yiiframework.com/doc/api/1.1/CList

I sometimes use this really simple implementation to give me a rough and ready collection.

Normally the main requirement of a collection is enforcing a group of one type of object, you just have to setup a basic class with a constructor to implement it.

class SomeObjectCollection {

   /**
    * @var SomeObject[]
    */
   private $collection = array();

   /** 
    * @param SomeObject $object1
    * @param SomeObject $_ [optional]
    */
   function __construct(SomeObject $object1 = null, SomeObject $_ = null) 
   {
       foreach (func_get_args() as $index => $arg) {
           if(! $arg instanceof SomeObject) throw new \RuntimeException('All arguments must be of type SomeObject');
           $this->collection[] = $arg;
       }
   }

   /**
    * @return SomeObject[]
    */
   public function getAll()
   {
       return $this->collection;
   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top