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

后端 未结 1 1649
情深已故
情深已故 2021-01-06 07:26

I check myself and see that, the order of execution on Controller is \"onConstruct\" then \"initialize\", while on Model is \"initialize\" then \"onConstruct\".

So w

相关标签:
1条回答
  • 2021-01-06 08:02

    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.

    0 讨论(0)
提交回复
热议问题