Fatten up your Models

CakePHP models, unlike super models should be fat. It’s a good practice to keep redundant code out of your controllers. Here’s a quick example on how you can keep your controllers skinny and models fat.

Let’s say you need to get a list of all public and active products…

[sourcecode language=’php’]
$productList = $this->Product->find(‘list’, array(
‘conditions’ => array(
‘Product.is_public’=>1,
‘Product.status’=>2)),
‘Product.name ASC’);
 [/cc]

So the above code will select all products where is_public = 1 (assuming that means the products are public) and status = 2 (let’s say 2 means active).

Now if you have a bunch of different actions that require you to get such a list you’d have to repeat this same code over and over. Sounds like a bad idea…

Instead you should move this code into your Product model and create a method there called getList (for example). Remember that in the model you won’t need $this->Product. Adjust the code to read $this->find, the rest remains the same.

Now in the controller all you have to do is:

[sourcecode language=’php’]
$this->Product->getList();
[/cc]

You could even make getList more interesting by allowing the user to pass parameters, such as values for is_public and status.

Not only does this help to keep your code cleaner, but if your rules change to say that you need to get all products with status 3 instead of 2 you only need to modify the code in your Product model, rather than in a lot of different actions.

%d bloggers like this: