I check myself and see that, the order of execution on Controller is "onConstruct" then "initialize", while on Model is "initialize" then "onConstruct".
So why the order of execution of these methods is different on Controller and Model? Any idea?
Besides the same name, initialize
has different purposes in Models and Controllers:
For Models initialize will mostly take care of initializing the model's metada(column mapping, model relationships, etc) that's why it's called before the constructor since all model metadata is stored statically in the model class (btw that's why initialize
is called just once per request per model).
For Controllers initialize
is just called if the route is matched successfully(the required action exists and was requested properly) and the current user has privileges to execute that action according to the ACL(if any). So the controller is constructed first to check those things (onConstruct
is fired), and then if everything goes well you can initialize your controller for real (initialize
is fired).
Now talking about onConstruct
, both in Models and Controllers, that's just a replacement for native constructors. The implementation of a __construct
method in your classes isn't recommended because they will be called by the framework that expects a specific method signature for it. Also you'll need to remember to always hook the parent constructor manually. So, by using the onConstruct
event instead we're avoiding all these issues.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With