Using collections to ease the handling of (propel-result-)arrays
In this post, I want to present a different view of dealing with arrays adopted from the Java world:
The Collections.
class Collection implements Iterator
{
protected $objects;
public
function __construct
(array $objects =
array()) {
$this->objects = $objects;
}
/**
* Returns an array containing all of the elements in this collection.
*/
public function toArray()
{
return $this->objects;
}
/**
* @see Iterator::current()
*/
{
}
/**
* @see Iterator::key()
*/
{
return key($this->
objects);
}
/**
* @see Iterator::next()
*/
{
return next($this->
objects);
}
/**
* @see Iterator::rewind()
*/
{
return reset($this->
objects);
}
/**
* @see Iterator::valid()
*/
public function valid()
{
return false !== $this->current();
}
}
As seen above, the Collection is a simple class taking an array of objects in its constructor. It has a getter for the passed array and implements the Iterator interface to untilize iterating the object by using the php foreach construct:
$data =
array(new MyObj
(),
new MyObj
),
new MyObj
());
$collection = new Collection($data);
foreach ($collection as $myObj)
{
// do something for each MyObj-instance
}
Especially in the context of retrieving propel objects (by XxxPeer::retrieveByXXX()), you (sometimes) need to set up a domain specific business logic on top of the Collection. This is done by creating s special implementation for each type:
abstract class Collection
{
// ... same code as in first example but class is declared as abstract
}
class TagsCollection extends Collection
{
public function getNamesAsString($delimiter = ', ')
{
// ...
}
}
class TagPeer extends BaseTagPeer
{
/**
* @return TagsCollection
*/
public
static function retrieveForEntry
(Entry
$entry) {
$c = new Criteria();
$c->add(self::ENTRY_ID, $entry->getId());
$tags = self::doSelect($c);
return new TagsCollection($tags);
}
}
// ...
$tags = TagPeer::retrieveForEntry($entry);
foreach ($tags as $tag)
{
// works as expected
}
echo $tags->
getNamesAsString();
This concept beautifies your code and reduces code duplication (in some case).