php – What is Lazy Loading and Eager Loading?

Question:

  • What is Lazy Loading and Eager Loading ?

I saw these terms in a documentation, but I didn't understand them very well, so my doubt is to know what these terms mean and I would like to, if possible, restrict the scope of the answer/question to PHP and CakePHP (MFramework MVC with built-in ORM) because these are the technologies I'm having the most contact with lately and where I've seen the terms.

Answer:

Eager Loading

It is the Load where all related classes are loaded in the same query. The ORM, usually through Joins, will bring all related entities.

Example of use

You have a List entity, where it has several Item entities (one to many), in your List entity there is an attribute with a Collection of Items .

When you run a Find() or some command to bring these objects, all their relations are loaded immediately, that is, all your Items in memory will already be loaded in your List (in this example).

Therefore, these objects can already be referenced.

In certain cases, Eager loading becomes unnecessary, because not always when you load an entity you want to have the related entities loaded in memory.

Example of loading with Eager loading of Items related to List :

// Usando em conjunto com o find()
$query = $listas->find('all', ['contain' => ['Items']]);

// Como um método query no objeto
$query = $listas->find('all');
$query->contain(['Items']);

Note that more than one relationship can be defined with the contain

Lazy Loading

as the name says, it is a lazy load, when you execute a query for a certain Entity its relations are not loaded into memory by the initial query, however, when executing some method that calls these records, another query will be executed to fill these related entities.

Example

Following the example of Lists and the related entity Item , if you used for example a List GetItems() method, the ORM would run a query and load those entities for you.

Loads in CakePHP

According to CakePHP's documentation Lazy Loading must be implemented by you, ie the ORM will not do this automatically.

Example of use

In this example the List x Item relationships are manually loaded into the List entity.

 namespace App\Model\Entity;

 use Cake\ORM\Entity;
 use Cake\ORM\TableRegistry;

class Lista extends Entity
{

    protected function _getItems()
    {
        $items = TableRegistry::get('Items');
        return $items->find('all')
            ->where(['lista_id' => $this->id])
            ->toArray();
    }

}

Eager X Lazy CakePHP Documentation: http://book.cakephp.org/3.0/en/orm/entities.html#lazy-loading-associations

Scroll to Top