Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Phalcon: the order of 2 functions "initialize" and "onConstruct" in Controller and Model

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?

like image 285
Viet Nguyen Avatar asked Dec 14 '22 22:12

Viet Nguyen


1 Answers

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.

like image 171
kbtz Avatar answered Dec 28 '22 07:12

kbtz