More on my github’s brute code.
Lazy Load is a simple design pattern that basically consists in making related data to be easily fetched by the domain model.
The implementation of the pattern happened through a behavior that will allow you to get related data with simple, readable and beauty method calls:
$this->User->getProfile();
and the User’s Profile data you shall have.
$this->User->getComments();
and the User’s Comments list will be returned.
“But I want the whole data man” – i hear you shout:
$this->User->getComments('all');
“Nope, I want it to use my custom method as you and Daniel shown” – ok:
$this->User->getEvents('expecteds');
All relationships are supported:
$this->Project->getMilestones();
$this->Project->getOwner();
$this->Child->getFriends();
$this->Post->getTags();
$this->Tag->get_posts(); // if you like this style, enjoy then
But be semantic, it can’t getTask if it actually hasMany Task:
$this->Project->getTask(); // Exception thrown here
$this->Project->getTasks(); // yes sir, here they are.
Default behavior is to return a find(‘first’) for belongsTo and hasOne associations, and a find(‘list’) for hasMany and hasAndBelongsToMany, but you can override it, as shown above, and here again:
$this->Node->getComments(); // find('list') returned
$this->Node->getComments('threaded'); // find('threaded') will be returned
$this->Comment->getAuthor(); // find('first')
And you can even get the related model instance for belongsTo and hasOne associations, just pass a boolean true as param:
// get a Baker instance already setted with the related model data
$Baker =& $this->Cake->getBaker(true);
$cakes = $Baker->getCakes();
About the beauty mentioned, we can use controller’s actions as examples:
class ProjectsController extends AppController {
function view($id = null) {
if ($this->Project->exists()) {
$data = $this->Project->read();
$assignedUsers = $this->Project->getAssignedUsers();
$hotTickets = $this->Project->getTasks('hots');
$this->set(compact('data', 'assignedUsers', 'hotTickets'));
}
}
}
Pretty RAD prone in my opinion.
No configuration needed, it’s just plug and play.
Be sure to get the tests too, so you can assure it works well.
Thanks and “good night ladies, good night…”
Tagged: Behavior, Data Handling, LazyLoaderBehavior, Model, Open Source
