Answer the question
In order to leave comments, you need to log in
How to get rid of code duplication in SeachModel Yii2?
Good day colleagues.
I'm new to Yii2 , please point me in the right direction.
Started working on a project. I create various directories in a DB. Each such directory has the same fields, [ create_at , update_at ].
Further, everything is according to the textbook ... Gii model, CRUD
So, in each model you have to write the same code for searching by time [ create_at , update_at ]. and a few more fields. As you understand, this whole thing smells bad and looks more like g ... code.
There is an idea to make some kind of basic BaseSeachModel and from it to enjoy the rest of the models. Or there are some more beautiful solutions.
Answer the question
In order to leave comments, you need to log in
Your vision of inheritance will lead to shitty code. Yii2 already has many inheritances and disagreements with SOLID.
1 Site Filter Form = 1 SearchModel
First understand what a SearchModel is and you will understand its responsibility. This is a filter form that receives data from the user and makes a selection of data according to the passed parameters from the database. It will seem to you that you are duplicating code, but it is. You separate search models for specific tasks.
Example: On the main page - you need a filter form for one / two fields / pits. In advanced search, a filter form by several fields. If you have the same filtering options in different places, you use the same form in two places. If the data is different, create a new SearchModel. They can be as many as needed. For every task.
An important point that is most often used in Yii SearchModel is inheritance from the main Acrive Record model. This is absolutely impossible to do. This is only done for rapid development. With this development, all the fields of the base stick out "out". I recommend that all SearchModels be inherited from a simple model (Model class). Then the Search Model will be safer and it will be just a form, not a form with additional features.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question