The Smart Method of Loading Collections
One fairly unknown feature of Magento collections is that you actually don’t have to call ->load() on a collection before being able to access the items in the collection. So you can do this:
$orders = Mage::getResourceModel('sales/order_collection')->addAttributeToSelect('*'); # The load method is not necessary, as iterating through a collection automatically loads it, if it hasn't already been loaded. # $orders->load(); foreach($orders as $order){ echo 'Order Id: ' . $order->getId() . "\n"; } |
The base Varien_Data_Collection class implements the IteratorAggregate (http://php.net/manual/en/class.iteratoraggregate.php) interface which extends the Traversable (http://www.php.net/manual/en/class.traversable.php) interface. When a class extends the Traversable interface, it guarantees that that class can be iterated through using foreach(). When foreach is called on a collection, it calls the getIterator() method in the Varien_Data_Collection class and uses the value returned from that method as the value that the foreach iterates through. This is the getIterator() method:
public function getIterator() { $this->load(); return new ArrayIterator($this->_items); } |
This auto-loading functionality works for both EAV and flat-table collections.
As you can see, a collection ensures that it is loaded before running through a foreach loop. Note: collections can only be loaded once per instantiation. If you want to reload a collection, you have to call the clear() method, and then reset the select and filters before calling the load() method again.
Knowing that collections function in this way allows you to write code without explicit calls to load(). This ultimately should result in more flexible code. You can have a method in a block that loads a collection. That collection can then either be called by a template file and iterated through, or you can have another method that loads the collection from the first method, and then adds additional selects/filters to it. This practice of not explicitly calling the load() results in more flexible and reusable code.
This entry was posted on Wednesday, February 10th, 2010 at 2:15 pm and is filed under Magento Development. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
May 6th, 2011 at 10:18 pm
With havin so much content do you ever run into any issues of plagorism or copyright infringement? My site has a lot of completely unique content I’ve either written myself or outsourced but it looks like a lot of it is popping it up all over the internet without my permission. Do you know any solutions to help reduce content from being stolen? I’d really appreciate it.
January 6th, 2012 at 4:42 pm
Where to find professional driving instructors…
[...]You could look in the local paper or search Google to ‘Find Driving Instructors’.[...]…