For the sake of brevity, I’ll simplify my example; say I have an index.php file in which I instantiate the repository class like this:
$itemRepos = new ItemRepository();
$allItems = $itemRepos->getAll();
and at this point in the variable $allItems I have all the records returned to me from the database, and now I can iterate through them.
But now, I would need to (because of the memory issues) read the items from the database one by one, and surely, in the index.php file I could make a connection to the database and use the while loop like this for example:
while ($row = mysql_fetch_row($result)){
//do stuff
}
and thus reading the rows one by one, but I don’t want to do it like that and I was wondering how do I achieve the same thing by using the OOP principles, so without putting the db connection logic into the index.php file, and by (somehow) putting this in the Repository class.
I do think some kind of pattern or ‘something’ already exists for this, so please do push me in the right direction.
When you don’t want to expose implementation details but still want to be able to iterate, you should use the
Iterator pattern. The purpose is to provide a unified way that clients can iterate over something, while keeping the underlying implementation encapsulated.PDO offers an iterator over result sets without you having to code anything. But, if you must stay with the mysql_* extension for now, you can write your own iterator by implementing Iterator.
You might actually find some example code in the manual for making an iterator to encapsulate a mysql_* result set.