問題描述
我認為執行的順序是init()、preDispatch()然后action()被調用.
我是否應該在 init() 或 preDispatch() 中初始化我的變量,這些變量在所有操作中都很常見?我見過有人使用這兩個函數進行初始化.可能顧名思義,它應該在 init() 中完成,但是在 preDispatch() 中會發生什么樣的事情?
init() 和 preDispatch() 函數調用之間會發生什么?
首先為 Zend_Controller_Plugin_Abstract
的實例調用 preDispatch()
.這里有請求和響應對象,因此您可以過濾請求或使用請求中的信息做一些準備.
Zend_Controller_Action
的 init()
接下來作為構造函數的一部分被調用.它可以幫助您初始化控制器,而無需覆蓋和重復構造函數的簽名(Zend_Controller_Action::__contruct()
).
控制器的preDispatch()
方法在這里被調用.您可以調用 $request->setDispatched(false)
來跳過當前操作 - 不確定您是否可以在 init()
然后調用您的操作方法(例如viewAction()
).在這里,您可以執行正常的工作,例如從模型中獲取內容并填充視圖.
所以區別現在應該很清楚了:
- 如果您想在所有操作之前執行某些操作 - 將其放入插件并使用其中一個鉤子(除了
preDispatch()
之外,還有routeStartup
和 其他), - 如果你想在控制器中的每個動作之前 -
init
或preDispatch()
, - 如果僅針對單個操作 - 操作本身.
init()
和 preDispatch()
函數調用之間會發生什么?
幾乎什么都沒有 - preDispatch()
被執行了,如果你還沒有調用 $request->setDispatched(false)
,動作就會被執行.>
I think the order of execution is init(), preDispatch() and then action() is called.
Should I initialize my variables, which are common among all actions, in init() or preDispatch()? I've seen people using both functions for initialization. Probably as the name suggests it should be done in init() but then what kind of stuff would go in preDispatch()?
What happens between init() and preDispatch() function calls?
First preDispatch()
is called for instances of Zend_Controller_Plugin_Abstract
. Here you have the request and response objects, so you might filter the request or do some preparation using the information from the request.
init()
of the Zend_Controller_Action
is called next as part of the constructor. It's there to help you initialize your controller, without having to override and repeat the signature of the constructor (Zend_Controller_Action::__contruct()
).
The controller's preDispatch()
method is called here. You can call $request->setDispatched(false)
to skip the current action - not sure if you can do that in init()
Then your action method is called (viewAction()
for example). Here you do your normal work like fetching stuff from the model and populating the view.
So the distinction should now be clear:
- If you want something to be executed before all actions - put it in a plugin and use one of the hooks (besides
preDispatch()
there isrouteStartup
and others), - if you want before every action in a controller -
init
orpreDispatch()
, - if only for a single action - the action itself.
What happens between
init()
andpreDispatch()
function calls?
Almost nothing - preDispatch()
is executed, and if you haven't called $request->setDispatched(false)
, the action is executed.
這篇關于Zend Framework:控制器對象中的 init() 和 preDispatch() 函數有什么區別?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!