PHP code example of jeremyharris / cakephp-lazyload

1. Go to this page and download the library: Download jeremyharris/cakephp-lazyload library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

jeremyharris / cakephp-lazyload example snippets



namespace App\Model\Entity;

use Cake\ORM\Entity;
use JeremyHarris\LazyLoad\ORM\LazyLoadEntityTrait;

class User extends Entity
{
    use LazyLoadEntityTrait;
}


// get an entity, don't worry about contain
$programmer = $this->Programmers->get(1);


// beers is lazy loaded
foreach ($programmer->beers as $beer) {
    // brewery is lazy loaded onto $beer
    echo $programmer->name . ' drinks beer ' .  $beer->name . ' from ' . $beer->brewery->name;
}


$programmer = $this->Programmers->get(1, [
    'contain' => [
        'Beers'
    ]
]);

// beers is loaded via the eager loader
$programmer->beers;
// brewery is lazy loaded onto $beer[0]
$programmer->beers[0]->brewery;


$programmer = $this->Programmers->get(1);

// beers is lazy loaded
$programmer->beers;
// remove beers from the entity
$programmer->unsetProperty('beers');
// this now returns false
$programmer->has('beers');
// if we want access to beers again, we can manually load it
$programmer = $this->Programmers->loadInto($programmer, ['Beers']);


namespace App\Model\Entity;

use Cake\ORM\Entity;
use Exception;
use JeremyHarris\LazyLoad\ORM\LazyLoadEntityTrait;

class User extends Entity
{
    use LazyLoadEntityTrait {
        _repository as _loadRepository;
    }

    protected function _repository()
    {
        try {
            $repository = $this->_loadRepository();
        } catch (Exception $e) {
            return false;
        }
        return $repository;
    }
}