Answer the question
In order to leave comments, you need to log in
Why is the model rendered in the controller?
Often, looking at the code of other modules, one comes across such that the model logic is transferred to the controller, for example
public function actionAjaxSearch()
{
Yii::$app->response->format = Response::FORMAT_JSON;
$query = Post::find()
->select(['id', 'title'])
->andWhere(['like', 'title', Yii::$app->request->post('title ')])
->limit(10);
if ($postType = Yii::$app->request->post('type')) {
$query->andWhere(['type' => $postType]);
}
return $query->all();
}
After all, the selection from tables and everything else should be carried out in the model, why then is the model found in the controller almost everywhere?
Answer the question
In order to leave comments, you need to log in
The logic for constructing a query for good should be in the model, because it's part of the business logic. The controller only needs to process the user request and work with the business logic class. Also, some aspects of query generation can be taken out in ActiveQuery
PS, do not forget that the model in MVC and the YII model are different concepts
So faster.
Create a separate function to get all the records you need in some mapper/repository/model, as you please. And only call it from the controller.
As a result, there will be something from the category:
public function actionAjaxSearch()
{
Yii::$app->response->format = Response::FORMAT_JSON;
return Post::findAllEntities(Yii::$app->request->post);
}
Occurs everywhere and correctly - these are two different concepts.
On a good note, a separate model is made for searching, it is inherited from the main one, there are examples in the yii2 docks, and the standard crud generated via gii does this. This is correct, it is convenient, but when writing with pens, it takes longer. Apparently that's why they often do it wrong.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question