I am building an abstraction layer for a data provider. Each component of the data has it's own repository which returns collections of entities. The repository has three public methods:
public function fetchAll();
public function findById($id);
public function find(Query $query);
When the 'fetchAll' method is called, a PDO statement is created and executed. The result of this query is then initialised into a ZF2 HydratingResultSet object so that when it's iterated, each item will be correctly created as an entity by the hydrator.
The problem arises however, when I try to establish how best to 'set' this result set on the collection. So far I've done the following:
-
Set the 'HydratingResultSet' object directly on the collection and 'proxied' the iterator interface methods through to the result set property in the collection. For example:
protected $hydratingResultSet; public function current() { return $this->hydratingResultSet->current(); }
-
Iterated through the result set and added each hydrated entity to the collection. For example:
foreach ($hydratingResultSet as $entity) { $collection->add($entity); }
The former seems to cope much better with large result sets as the query buffering means that the entities are only being hydrated as the collection is iterated. However, I'm concerned that I've coupled the driver to closely with the collection which may derail some caching strategies. Additionally, it means that I wouldn't ever be able to serialize or un-serialize the collection as the PDO statement obviously doesn't allow for this.
The latter method however, quickly runs out of memory in PHP which large result sets which is understandable. Ideally I'd prefer to use this way of doing things as it'll be a lot better to deal with but the memory issues are blighting me currently.
Could anyone offer any advice on this? Is there a different option to consider or a different way of approaching the problem?