Zend Framework 2中init()和onBootStrap()之间的区别?

Neo*_*yte 4 php zend-framework2

我正在读一本关于ZF2的书,它将init()和onBootStrap()都称为Module.php中的函数,这些函数在每个页面加载期间被调用,因此应该尽可能轻量级.

除了略有不同的签名:

init(ModuleManager m)
onBootStrap(MvcEvent e)
Run Code Online (Sandbox Code Playgroud)

我正在努力确定何时应该使用哪种,以及出于什么原因.在本书中,两种方法都被用于附加(不同)事件.有人可以提供两者之间差异的明确定义,以及一些具体的例子,我会使用一个而不是另一个(以及为什么)?

谢谢!

小智 5

你的问题的答案是时间和目的的问题.该init()功能始终在onBootstrap()功能之前发生.由于目的init()是初始化模块(例如,具有其自己的独立配置选项),因此在init()给定模块运行时可能尚未加载其他模块.但是,onBootstrap()在所有模块初始化之后运行,它可以侦听不同的事件.

有关这方面的更全面的解释可以在http://framework.zend.com/manual/2.3/en/modules/zend.module-manager.module-manager.html 以及文档http:/中的下一页 找到. /framework.zend.com/manual/2.3/en/modules/zend.module-manager.module-class.html

就个人而言,我使用init()在一个模块中初始化一个Propel库,我Propel使用http://4zend.com/integrate-propel-orm-with-zend-framework-2/上的技术创造性命名.

onBootstrap()用来检查我的访问控制列表(哪些用户可以访问哪些资源)并相应地限制访问,如下所示:

public function onBootstrap(\Zend\Mvc\MvcEvent $e) {
    // After the route event occurs, run the checkAcl method of this class
    $e->getApplication()->getEventManager()->attach('route', array($this, 'checkAcl'));
}
Run Code Online (Sandbox Code Playgroud)