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 for each 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.

Share it

Topics

Related Posts

Google and Yahoo Have New Requirements for Email Senders

What ROAS Really Means

Everything You Need to Know About Updating to Google Analytics 4

Contact Us