Custom Model Functions

Maybe it's my long time procedural approach to application development but when I jumped into cake, I used much of the functionality to simply replicate my existing development process.

For example, the model was used as a database connection class. If it didn't do what I wanted, I'd set up a custom query in the controller, return the results, process, and feed the data to the view.

Then I started thinking of all the other things I'd need to do with it, like XML or JSON responses. I'd end up duplicating the same code just to return the exact same result set. Then it dawned on me. I should be using the model to return the final result set, not the controller.

My rule of thumb now is, if I have custom SQL, do it in the model, not the controller. My second rule is, if I have to filter the results for any reason, do it in the model, not the controller.

Published August 01, 2006 · Updated August 01, 2006
Categorized as CakePHP
Short URL:


2 Comments · RSS feed
Paul (WebbedIT) said on December 13, 2008

Sorry for comments on really old posts, but you are covering a bunch of topics which are similar to thoughts going round my head whilst evaluating CakePHP.

Back to the above ... how would you then treat the following, which I currently have sitting in my controller?

function index() {
    array('hasOne' => array('Agency', 'Household', 'Scheme')),
  if ($this->authUser['User']['user_group_id'] < 3) {
    $this->set('data', $this->paginate('Organisation', array(
      'Organisation.is_deleted' => '0',
      'Organisation.scheme_id' => 'NULL'
  } elseif ($this->authUser['User']['user_group_id'] == 3) {
    $this->set('data', $this->paginate('Organisation', array(
      'Organisation.is_deleted' => '0',
      'OR' => array(
      '' => $this->authUser['Scheme']['id'], 'Organisation.scheme_id' => $this->authUser['Scheme']['id']

Would you check the 'user group' value in the controller then call a specific function in the model, or is my use of conditions within the controller the right way to do it? (not that there probably is a RIGHT way to do anything)

Jonathan Snook said on December 13, 2008

@Paul: I think you've nailed it on the head in that there's no right or wrong way to do things, per se. In your particular example, I'm not sure things would be simplified any further by pushing that logic into a Model.

Sorry, comments are closed for this post. If you have any further questions or comments, feel free to send them to me directly.