Yii loadModel method?

So it was not long into my Yii development days that I began to notice this awful method that seemed to crop up more and more in other Yii developers code bases.

This is the so called “loadModel” method and it looks something like this …

The idea behind this method is that it is called from other methods in the same controller as itself to return a loaded model for use in the method. I do not understand the point of this method and I never have. I have never used it in any of my Yii 1 or Yii 2 code even though a lot of developers did.

Why is a method needed for loading models?

Please note that this method is only for loading existing models and not creating new ones so the intent behind the method could not have been “It is an easy location to change the model name if I need to so as I do not have to change it in multiple places if ever I need to change it”.

If this had of been the intent then the method would have been written like this …

As I will still need to declare the model separately when creating new models in the controller as the original method did not handle the creation of a new model.

Also a lot of the developers using the “loadModel” method are using different models in their controller anyway which are different from the model loaded in the “loadModel” method, so again the benefits of having the “loadModel” method seem non-existent.

Another so called benefit which could be tried to passed off as genuine is the use of the exception. If the model is not loaded then throw an exception saying the page does not exist.

The test to see whether a user can access the page and the test to see if the record for the model exists based on its ID is normally and best handled in the user permissions / RBAC so it is not needed in the controller.

My conclusion to this is that there is no benefit to using the “loadModel” method and it is more of a gimmick which developers have copied from other developers without thinking about it.

2066 Total Views 1 Views Today

Leave a Reply

Your email address will not be published. Required fields are marked *