Array Collection implementation in PHP

Here is presented a simple implementation of the Collection interface that uses a standard PHP array. The array collection also uses the Array Iterator PHP implementation.

When removing objects, array is packed, to avoid index gaps.

The ArrayCollection class is tested with Array Collection Unit Test.

The Solution

require_once('ig/Collection.class.php');
require_once('ig/ArrayIterator.class.php');
 
/**
 * Collection implementation over standard PHP array.
 * @author Ivan Georgiev
 */
class ig_ArrayCollection extends ig_Collection {
	var $theData;
 
	/**
	 * Factory method that creates a new ArrayCollection instance and
	 * initializes it by adding all the elements from a given array.
	 *
	 * @param array $array An array of Object[] to add to the collection.
	 * @return ig_ArrayCollection A reference to the new ArrayCollection object.
	 */
	function & createFromArray($array) {
		$collection =& new ig_ArrayCollection();
		$collection->theData = $array;
		return $collection;
	}
 
	/**
	 * Adds an element (reference) to this collection.
	 * If element already exists, it will not be added.
	 *
	 * @param Object $obj Element to add to collection
	 * @return boolean Retruns true if element was added.
	 * @abstract
	 */
	function add(&$obj) {
		if ( $this->_objectIndex($obj) >= 0 ) return false;
		$this->theData[count($this->theData)] =& $obj;
		return true;
	}
 
	/**
	 * Remove an element (reference) from this collection.
	 * If element doesn't exist, it will not be removed.
	 *
	 * @param Object $obj Element to be removed.
	 * @return boolean Retruns true if element was removed.
	 * @abstract
	 */
	function remove(&$obj) {
		if ( ($index = $this->_objectIndex($obj)) < 0 ) return false;
		$lastIndex = count($this->theData) - 1;
		while ($index < $lastIndex) {
			$this->theData[$index] =& $this->theData[++$index];
		}
		unset($this->theData[$index]);
		return true;
	}
 
	/**
	 * Creates an iterator over the elements in collection.
	 * @return ig_Iterator Returns a reference to an iterator.
	 * @abstract
	 */
	function & iterator() {
		$it =& new ig_ArrayIterator($this->theData);
		return $it;
	}
 
	function _objectIndex(&$obj) {
		$numItems = count($this->theData);
		$result = -1;
		for( $index = 0; $index < $numItems; $index++ ) {
			$obj->_ig_arraycollection_reftest_ = true;
			if (isset($this->theData[$index]->_ig_arraycollection_reftest_)) {
				$result = $index;
			}
			unset($obj->_ig_arraycollection_reftest_);
			if ( $result >= 0 ) break;
		}
		return $result;
	}
 
}

As the ArrayCollection class is a concrete class, we provided also a Array Collection Unit Test.

See also: Collection Interaface in PHP, Iterator Interface in PHP, Array Iterator in PHP

 
php/util/arraycollection.txt · Last modified: 2009/10/31 23:39 (external edit)
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki