The query() function of the model is sometimes very practical as it allows you to execute any SQL statement you want. But to me it seems it is often used in a “wrong” way (I have to include myself *g*), in a way which works but is not that clean. I am talking about calling query() from the controller:

$this->MyModel->query('Here comes the SQL statement');

Sure, following the Cake conventions this is a valid usage of query(), as the function is public. But it introduces database-related code to the controller, which is a violation of the MVC pattern.

I think a cleaner solution is to move the SQL statement to the model. So the snippet from above can be refactored to:

// in the model
function doSomething() {
    $this->query('Here comes the SQL statement');
}

// in the controller
$this->MyModel->doSomething();

Ok, this solution needs more code, but it comes with some additional advantages:

  • it is easier to test
  • it is more readable (at least if you give the function a better name than I did)
  • the query can be re-used without copy & paste in other actions/controllers

What do you think about this approach?