Hi everyone! We are updating our current website to yii2. So far so good! We like the new active record. However, we are having a design doubt with the ModelSearch class that extends from the Model active record class.
Should we add all the additional conditions and joins to the search method or is it better to create new methods similar to search? Or it depends? If it depends, on what?
I think it depends on how complex the search parameters are and how many records are in the database. Here is an excellent tutorial by Kartik on some things you can do to modify the search method for eager loading, sort methods and labeling. If you are building enterprise level applications, you will need build the query and conditions with sql, and this can be very advanced stuff (so please don’t ask me for an example). The concept of how the controller calls the model and hands in the post data and validates is very sound in Yii 2 and easy to understand and work with. I think it’s wise to follow the Yii 2 way first, learn what you can learn, then modify from there if necessary.
Hi evercode! Thanks for answering. We followed that tutorial and even applied it to the listview. My question was more about: Should we modify the search method as much as we need or at some point it is wiser to create other search methods in the same class?
Any combination of modifying the search method and or creating new methods would be appropriate as long as you are getting the results you want. Yii 2 is meant to be very extensible, and with their inutitive architecture, they have succeeded in that. Don’t you just love the fact that you put all the search methods in this child model and keep them out of the parent model? I do. I think it makes for cleaner more organized code. This is just my opinion. The guide is of course the authoritative source for everything. I linked to the working with DB section and you might also want to check out the scopes section in there, for setting up defaults etc. Again with this architecture, we are getting a separation of responsibilities and I really like it.