Thursday, November 8, 2018

CakePHP : Implementing the Repository Pattern with CakePHP

Implementing the Repository Pattern with CakePHP


I must admit, my recent articles are becoming a bit obsessed around the repository pattern.  What can I say, I like it, it’s useful, and it’s not restrictive based on a language or a framework.

I’ve long professed how I dislike convoluted controllers.  CakePHP’s find method almost immediately causes this when used inside a controller.  More importantly, the code inside the find method is extremely unreadable.  This is almost more important than a large controller function!

This is where the repository pattern comes in.  At its most basic example (which some will consider overkill – you know who you are), I still think the repository pattern is clearer.

Here is an example using the regular find approach:
$user = $this->User->find('first', array('conditions' => array('id' => $id)));

Compared to a repository example:
$user = $this->UserRepository->GetById($id);

The code is almost identically; however, in the second example, it’s clear that if I were to “read” the code I am retrieving a user by id opposed to I’m finding the first user with the conditions of id being equal to the variable $id.

http://www.endyourif.com/implementing-the-repository-pattern-with-cakephp/

No comments:

Post a Comment