我正在使用Kohana 3.2,我在調用另一個控制器中的控制器的輸出時出現問題。如何在控制器內使用控制器?
我想要什麼......
在一些網頁我有一個菜單,在別人我不知道。我想利用HMVC請求系統的靈活性。在頁面的控制器中,我想調用另一個負責創建菜單的控制器。
我有多麼的時刻:
文件menu.php:
<?php defined('SYSPATH') or die('No direct script access.');
class Controller_Menu extends Controller
{
private $_model = null;
public function __construct(Request $request, Response $response)
{
parent::__construct($request, $response);
$this->_model = Model::factory('menu');
}
public function action_getMenu()
{
$content = array();
$content['menuItems'] = $this->_model->getMenuItems();
// Render and output.
$this->request->response = View::factory('blocks/menu', $content);
//echo '<pre>'; print_r($this->request->response->render()); echo '</pre>'; die();
}
}
somepage.php
public function action_index()
{
$this->template->title = 'someTitle';;
$contentData['pageTitle'] = 'someTitle';
$contentData['contentData'] = 'someData';
#include the menu
$menuBlock = Request::factory('menu/getMenu')->execute();
$menuData = array('menu' => $menuBlock);
$this->template->menu = View::factory('pages/menu')->set('menu',$menuData);
$this->template->content = View::factory('pages/somePage', $contentData);
$view = $this->response->body($this->template);
$this->response->body($view);
}
如果我取消在menu.php以下行,我明白了提供的菜單:
//echo '<pre>'; print_r($this->request->response->render()); echo '</pre>'; die();
所以我想這部分是沒問題的。問題是在somepage.php以下行:
$menuBlock = Request::factory('menu/getMenu')->execute();
這給我回一個響應對象。無論我做什麼,我都不會在$ this-> template->菜單中獲得輸出。 ('menu',$ menuData);這個菜單可以在菜單中找到。
我必須做些什麼來讓$ this-> template-> menu包含視圖,所以我可以正確使用它?
我希望這一切都有道理。這是我想要做的方式,但也許我完全處於錯誤的軌道上。
我剛剛找到了答案,以我的問題 在somePage.php變化: $ menuBlock =支持::工廠( '菜單/使用getMenu') - >執行(); $ menuData = array('menu'=> $ menuBlock); $ this-> template-> menu = View :: factory('pages/menu') - > set('menu',$ menuData); 收件人: $ this-> template-> menu = Request :: factory('menu/getMenuBlock') - > execute() - > body(); 並在menu.php中更改: $ this-> request-> response = View :: factory('blocks/menu',$ content); 收件人: $ request = View :: factory('blocks/menu',$ content); $ this-> response-> body($ request); 我希望這會幫助別人。 – RWC
另外它不建議在你的代碼中使用__construct()方法。您應該使用before()(與__construct()相同)和after()(與__destruct()相同)方法。不要忘記調用parent :: before()too :) – egis