The Iterator Pattern is a design pattern that allows an object traverse through the elements of another class. This allows you to specify an iterator and allow for multiple different sets of data to be passed without changing the underlying structure that allows the iteration.
Take the below example:
1 |
Mage::getModel('catalog/product')->getCollection(); |
You will fetch a collection of product objects when you calls this method. You can also traverse (or loop) through this set and grab each individual object as well.
1 2 3 4 5 |
$collection = Mage::getModel('catalog/product')->getCollection(); foreach($collection as $product) { Zend_Debug::dump(get_class($product)); // returns 'Mage_Catalog_Model_Product' } |
When you call the getCollection() method, you will return a class that is designated to be the iterator for collections of data. This is true for all model setups inside Magento. In this case, you will return Mage_Catalog_Model_Resource_Product_Collection . This class inherits, (through a series of other classes) the Varien_Data_Collection class. This class allows the getting and setting of items in the collection. Note the methods addItem() , removeItemByKey() and getIterator() .
When you loop
$collection through a foreach, PHP calls the
getIterator() method. This method returns the ArrayIterator
class with the items set inside of it.
Now you know the magic behind the collections in Magento and how to fetch them with the Iterator Pattern.
Love it? Hate it? Want more? Leave me a comment and let me know!