2010-06-27 107 views
3

如何轉發到同一控制器內的其他動作,避免重複所有的調度進程?Zend Framework _forward在同一控制器內的其他動作

例子: 如果我指向用戶控制器的默認操作爲的indexAction()這個函式裏面我使用_forwad(名單')......但所有調度proccess重複..我不認爲

什麼是正確的方式?

回答

6

通常,您將安裝路徑以將您的用戶重定向到適當的(默認)操作,而不是索引操作(請閱讀如何使用Zend_Router從給定路徑重定向)。但是如果你真的想要直接從控制器中獲得(但是這被稱爲「編寫黑客代碼來實現某些髒東西」),你可以手動執行所有操作。

更改「查看腳本」被渲染,然後打電話給你的操作方法....

// inside your controller... 
public function indexAction() { 
    $this->_helper->viewRenderer('foo'); // the name of the action to render instead 
    $this->fooAction(); // call foo action now 
} 

如果你傾向於使用這種「把戲」的時候,也許你可以寫一個基本的控制器,你延長你的應用程序,它可以簡單地有一個方法,如:

abstract class My_Controller_Action extends Zend_Controller_Action { 
    protected function _doAction($action) { 
     $method = $action . 'Action'; 
     $this->_helper->viewRenderer($action); 
     return $this->$method(); // yes, this is valid PHP 
    } 
} 

然後從你的行動調用的方法...

class Default_Controller extends My_Controller_Action 
    public function indexAction() { 
     if ($someCondition) { 
     return $this->_doAction('foo'); 
     } 

     // execute normal code here for index action 
    } 
    public function fooAction() { 
     // foo action goes here (you may even call _doAction() again...) 
    } 
} 

備註:這不是官方的做法,但它的一個解決方案。

0

如果您不想重新發送,則沒有理由不能簡單地調用該操作 - 它只是一個函數。

class Default_Controller extends My_Controller_Action 
{ 
    public function indexAction() 
    { 
     return $this->realAction(); 
    } 

    public function realAction() 
    { 
     // ... 
    } 
} 
0

您也可以創建一個路線。例如,我在我的/application/config/routes.ini一節:

; rss 
routes.rss.route    = rss 
routes.rss.defaults.controller = rss 
routes.rss.defaults.action  = index 

routes.rssfeed.route    = rss/feed 
routes.rssfeed.defaults.controller = rss 
routes.rssfeed.defaults.action  = index 

現在你只需要一個動作,那就是指數的行動,但requess RSS /飼料也去那裏。

public function indexAction() 
{ 
    ... 
} 
+1

不,謝謝,我想從控制器,使用前路由重定向... – ovitinho 2013-08-02 18:09:22

1

我們還可以用這個幫手重定向

$this->_helper->redirector->gotoSimple($action, $controller, $module, $params); 

    $this->_helper->redirector->gotoSimple('edit'); // Example 1 

    $this->_helper->redirector->gotoSimple('edit', null, null, ['id'=>1]); // Example 2 With Params 
相關問題