Follow @endyourif rss Facebook LinkedIn

Implementing the Repository Pattern with CakePHP

Published on Jun 3, 2013

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.

So if you are sold, letís continue with a full suite exampleÖ

Why the Repository Pattern

Published on May 20, 2013

After the incredible reaction to a recent blog post, Entity Framework Beginnerís Guide Done Right, I feel like before writing some more code to further the basic example, Iíll take a step back and explain my beliefs in the repository pattern.

I was really overwhelmed with the reaction; what started with a simple 30 minute blogging effort has turned into something absolutely incredible.† The original post was really a starting point about not placing direct querying and saving to the database mingled with the core code.

Please note, these are my thoughts on the pattern based on current and previous pain points that Iíve/am experiencing and Iíd love to hear others input in making things better.