問題描述
是否可以在zend框架中調用另一個控制器的成員函數,如果是,那么如何?
Is it possible to call the member function of another controller in zend framework, if yes then how?
<?php
class FirstController extends Zend_Controller_Action {
public function indexAction() {
// general action
}
public function memberFunction() {
// a resuable function
}
}
這是另一個控制器
<?php
class SecondController extends Zend_Controller_Action {
public indexAction() {
// here i need to call memberFunction() of FirstController
}
}
請解釋我如何從第二個控制器訪問 memberFunction().
Please explain how i can access memberFunction() from second controller.
更好的想法是定義一個 AppController 并使所有常用控制器擴展 AppController,從而進一步擴展 Zend_Controller_Action.
Better idea is to define a AppController and make all usual controllers to extend AppController which further extends Zend_Controller_Action.
class AppController extends Zend_Controller_Action {
public function memberFunction() {
// a resuable function
}
}
class FirstController extends AppController {
public function indexAction() {
// call function from any child class
$this->memberFunction();
}
}
現在 memberFunction
可以從擴展 AppController
的控制器調用,作為簡單繼承的規則.
Now memberFunction
can be invoked from controllers extending AppController
as a rule of simple inheritance.
推薦答案
控制器并非旨在以這種方式使用.如果您想在當前控制器之后執行另一個控制器的動作,請使用_forward()
方法:
Controllers aren't designed to be used in that way. If you want to execute an action of the other controller after your current controller, use the _forward()
method:
// Invokes SecondController::otherActionAction() after the current action has been finished.
$this->_forward('other-action', 'second');
請注意,這只適用于操作方法(memberAction"),不適用于任意成員函數!
Note that this only works for action methods ("memberAction"), not arbitrary member functions!
如果 SecondController::memberFunction()
做了一些跨多個控制器需要的事情,把代碼放在一個動作助手或庫類中,這樣兩個控制器就可以訪問共享的功能而不必依賴互相依賴.
If SecondController::memberFunction()
does something that is needed across multiple controllers, put that code in a action helper or library class, so that both controllers can access the shared functionality without having to depend on each other.
這篇關于在zend框架中調用其他控制器的成員函數?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!