我在看 this了解 Zend 的 MVC 请求生命周期。
但是我想不出在 zend 中我会使用 Controller 的预调度方法的任何情况,对于我想在 Controller 操作之前执行的代码来说,init 方法还不够。
什么应该在 Controller 的预调度中而不是 init 中。
能给我举个例子吗 ?
最佳答案
见 Zend_Controller_Action - Object Initialization和以下部分Pre and Post Dispatch Hooks .他们都详细介绍了两者以及 Action Controller 本身。init()
更多用于设置 Controller 对象并进行可用于所有操作的初始化。自 init()
在 preDispatch()
之前运行,您在 init()
中设置的任何内容可用于 preDispatch()
使用。虽然可以从 init()
转发或重定向,最佳做法是从 preDispatch()
开始因为它在调度 Controller 操作之前运行。
从手册:
Note: Usage of init() vs. preDispatch() What is the difference between them (init and preDispatch), and what actions would you take in each?
The init() method is primarily intended for extending the constructor. Typically, your constructor should simply set object state, and not perform much logic. This might include initializing resources used in the controller (such as models, configuration objects, etc.), or assigning values retrieved from the front controller, bootstrap, or a registry.
The preDispatch() method can also be used to set object or environmental (e.g., view, action helper, etc.) state, but its primary purpose is to make decisions about whether or not the requested action should be dispatched. If not, you should then _forward() to another action, or throw an exception.
Note: _forward() actually will not work correctly when executed from init(), which is a formalization of the intentions of the two methods.
关于model-view-controller - Zend Controller 的预调度方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9323123/