6

I can meet many different approaches when using collections in Magento 2. Rarely, but sometimes I see that functions load() is used. Although without it there is no problem with accessing collection or its items. So what is the purpose of using it and do we really need load() collection in some situations?

6

If you just need to iter a collection there is no reason to call load.

If you see the basic implementation in \Magento\Framework\Data\Collection, method load is automatically called every time you try to access information.

Example:

public function getFirstItem()
{
    $this->load();

    if (count($this->_items)) {
        reset($this->_items);
        return current($this->_items);
    }

    return $this->_entityFactory->create($this->_itemObjectClass);
}

Or:

/**
 * Retrieve collection items
 *
 * @return \Magento\Framework\DataObject[]
 */
public function getItems()
{
    $this->load();
    return $this->_items;
}

For example, even method walk and each use a call to getItems(), so a call to load is always done.

I think you only need to call load when you need (for some reason) to load collection meta information before accessing items.

For example if you need to access filters or you need to trigger beforeLoad events on your items (see implementation of \Magento\Eav\Model\Entity\Collection\AbstractCollection::load() ).

This is only my opinion, I cannot see any reference in Magento 2 docs.

  • what do you exactly mean by meta information in context of collection? – Bartosz Kubicki Dec 23 '16 at 9:40
  • Like collection filters. – Phoenix128_RiccardoT Dec 23 '16 at 11:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.