I read about the concept “fat model and skinny controller”. I certainly would like to follow this concept.
Right now, all my controllers are fat and my models are skinny. I have a lot of find stmts (queries) in controllers that I would like to move to the models. But I have no idea on how to do it.
In which function of the model am I supposed to put the find statements? and after the set stmts in the model, will I be automagically able to view that data in the respective view?
Can someone please give me an example? I have already gone through the cakephp cookbook blog sample. And over there the find stmts are in the controller instead of the model. The model only contains the relationships and validations. I’m yet to see a model example containing find stmts.
The answers which have been given answer part of your question. You can use the find method without the Model class declaration (so
$this->find()instead of$this->Model->find()).To adhere to the “fat models, skinny controllers” principle, your models should hold most of the business logic of your application, while the controllers handle the data from the model that’s used by your views.
So, if you want to have all the
findlogic happening in your models, you should do the following.Product.php:
Note that you cannot use
$this->set()in your model, you should use it in your controller:ProductsController.php:
A populated
$productsvariable (if there are records in the revelant database table) will now be available in you view.This is a great article detailing the concepts of Cake and there’s another one in the Cookbook on MVC in general.