Phalcon:2 个函数“初始化"的顺序和“onConstruct"在控制器和模型中 [英] Phalcon: the order of 2 functions "initialize" and "onConstruct" in Controller and Model

查看:10
本文介绍了Phalcon:2 个函数“初始化"的顺序和“onConstruct"在控制器和模型中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我自己检查了一下,在Controller上的执行顺序是onConstruct"然后是initialize",而Model是initialize"然后是onConstruct".

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

那么为什么这些方法在Controller和Model上的执行顺序是不同的呢?有什么想法吗?

So why the order of execution of these methods is different on Controller and Model? Any idea?

推荐答案

除了同名之外,initialize 在 Models 和 Controllers 中有不同的用途:

Besides the same name, initialize has different purposes in Models and Controllers:

对于模型 initialize 将主要负责初始化模型的元数据(列映射、模型关系等),这就是为什么它被称为之前构造函数,因为所有模型元数据都是静态存储在模型类中(顺便说一句,这就是为什么每个模型每个请求只调用一次 initialize 的原因).

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).

对于 Controllers initialize 如果路由匹配成功(所需的操作存在并被正确请求)当前用户,则只会调用 initialize有权根据 ACL(如果有)执行该操作.因此,首先构造控制器以检查这些内容(onConstruct 被触发),然后如果一切顺利,您就可以真正初始化您的控制器(initialize 被触发).

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).

现在谈论 onConstruct,在模型和控制器中,它只是原生构造函数的替代品.在您的类中实现 __construct 方法不推荐,因为它们会被需要特定方法签名的框架调用.此外,您还需要记住始终手动挂钩父构造函数.因此,通过使用 onConstruct 事件,我们可以避免所有这些问题.

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.

这篇关于Phalcon:2 个函数“初始化"的顺序和“onConstruct"在控制器和模型中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆