How can I use model functions correctly according to the MVC pattern in CakePHP?

Can I do this in the controller :

$this->User->read(null, $id); $this->User->find('list'); 

Is it correct?

Am I using MVC correctly?

Can these simple functions be used in the controller? Or do I need to create these functions in a model? Like Model->getUser() , and use this function Model->read() .

I know that the functions that he called Model, but when I want to pass some parameters, and the function does big, for example:

 $this->User->find('all', array( 'conditions' => array( 'User.active' => true, 'User.group_id' => 3, 'User.age >=' => 18 ) )); 

Can I call this function in the controller or create a custom function in the model to call? How ... $this->User->findSomeCustomFunction($param1, $param2, $param3) ?

+4
source share
2 answers

TL; DR:

OK to invoke find() from your controller, however it is best to put all / all find () s in your models .

If you are used to placing all your find() in your models, this will greatly simplify your code in the long run.

Explanation / for example:

In this case, for example, you can start with a seemingly simple function:

 //User model public function getUsers() { return $this->find('list'); } 

But later, maybe you will need something more line by line:

 //User model public function getUsers($opts = array()) { $defaults = array( 'findType' => 'all', 'activeOnly' => true, ); $params = array_merge($defaults, $opts); $qOpts = array('conditions' => array()); //active only if(!empty($params['activeOnly'])) $conditions[$this->alias.'.active'] = 1; return $this->find($params['findType'], $qOpts); } 

(Sorry, if there are many ways to make this code better - it was just in my head - this gives you an idea.)

Saving all your find() in the Model also prevents you from searching for each controller every time you want to write find() to determine if you are using a similar find() somewhere else. If you program as a team, this can be a nightmare, and you will almost certainly duplicate the code.

+4
source

It is quite normal to call Model->find() from the controller. However, you will also want to follow the principles of DRY (Do not Repeat Yourself). It basically means "Don't copy-paste code everywhere."

So, if you find that you need to make this exact call to Model->find() from many controller actions, it is considered good practice to divert it to a function call against the model. So yes, your controllers then call $this->User->findSomeCustomFunction() .

+3
source

Source: https://habr.com/ru/post/1469045/


All Articles