2010-11-01 87 views
1

我想從cakephp中的.ctp文件調用控制器文件的動作。可能嗎?是的,比如何?請幫忙。例如, 我在控制器中有一個動作。 users_controller.php中來自ctp文件的呼叫控制器動作

<?php 
class UsersController extends AppController { 

    function get_category() { 
     .... 
    } 

} 
?> 

我想從/question/index.ctp文件調用它。

+4

你爲什麼要這麼做?這違反了良好的MVC慣例,對我來說,它尖叫着「某些東西沒有正確設置」。 – 2010-11-01 19:49:26

+0

+1是的,但.... – Leo 2010-11-01 20:54:55

回答

2

正確的方式做,這就是:

$this->requestAction(array('controller' => 'users', 'action' => 'get_category')); 

創建url the CakePHP way將提高性能(不必使用路由器)。也會一直工作,而這樣做:「users/get_category」可能會導致一些麻煩,當你不在索引頁面。

它應該只用於元素(特別是緩存),如果情況不同 - 請參閱Travis Leleu在他的評論中寫的內容。

+0

但它不會生成get_category.ctp文件的輸出。我也想顯示它的輸出。 – gautamlakum 2010-11-06 17:34:38

1

你可以這樣調用它$這個 - > requestAction( '控制'=> '用戶', '動作'=> 'get_category')

+0

更正$ this-> requestAction('users/get_category') – mentes 2010-11-01 19:38:47

+1

都會工作:) – 2010-11-01 19:51:32

+0

據我所知$ this-> requestAction('controller'=>'users' ,'action'=>'get_category')這個應該是$ this-> requestAction(array('controller'=>'users','action'=>'get_category'))我沒有嘗試過其他方式 – mentes 2010-11-01 19:54:26

2

應該指出,你不應該依賴requestAction作爲一種常見的做法。 requestAction是一個極其重要的調用,只能在您無法以其他方式組織代碼時使用。

理想情況下,您需要將所需的數據從控制器操作發送到視圖,而不是回撥至控制器。

function my_action() { 
    ... 
    $this->set('category', $this->getCategory()); 
}