CakePHP's Query method, directly written in the controller is not a bit inappropriate

Source: Internet
Author: User

The query () function of the model is sometimes very useful, and it can execute SQL statements wherever the data is needed.
But not where the query () method is invoked is appropriate. In particular, invoking the model's query () method directly in the controller

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

Calling the model's query method in the controller is not possible, but it introduces database-related code, which violates the principles of the MVC pattern

A cleaner solution is to move the SQL statements into the model, so the code above is refactored to:

In the model
function dosomething () {
$this->query (' Here comes the SQL statement ');
}
I in the controller
$this->mymodel->dosomething ();

Do not include database-related code in the controller, the code should be placed in the model, there are models to deal with

This scenario requires more code to be written, but it brings some advantages:

* Easy to test
* More readable
* Avoids the query code export replication between multiple controllers, making the code more concise

CakePHP's Query method, directly written in the controller is not a bit inappropriate

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.