Search code examples
phpyiisavebefore-save

YII - Why to use beforeSave() when you can code before Save() function


I am aware of functionality of function beforeSave() in YII that this function is used to perform something, which we want to perform before our data saved.

However, as far as we want to implement this before our data got save to database, can't we directly write this code before save() is calling (-> save () is storing out records to database )

Hence, I am not sure why exactly we need to create specific function like beforeSave () to perform action which we need to fire before Save() called, when we directly write that code before save() line as well.

can someone please explain this ? I have searched lot for reason of this but on every page, it redirect to explanation of beforeSave() function only.


Solution

  • Yii and other MVC frameworks have those kind of functions.

    While you can write your "before save" code in the controller, prior to the save() function - it's more recommended and useful to use the beforeSave() function.

    Reason 1: The M in the MVC

    The beforeSave relates to the model, so it would be more logical to have a code that handles the model's properties (fields) in the model's file rather than having that code in the controller.

    Reason 2: Saving is for insert & update

    You use save() when you insert a new record and also when you update an existing record. Without using the beforeSave built-in function, you'll have to have 2 instances of your "manual" before save code. ("Waste" of code lines)

    Reason 3: Saving a model from another controller

    What if you'll be asked to expand your application and now you'd have to face a new controller that need to save that same model (from some reason - just a possible scenario) - you'll have to copy your "before save" code to that controller. While if you're using the built-in beforeSave function - you don't.

    In conclusion, the main purpose of frameworks is to reduce the code you need to write while keeping anything logical (MVC separation). While you can do things differently, why not using what's already exists?