【发布时间】:2011-11-06 16:03:25
【问题描述】:
我正在使用 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 中得到输出。
$this->template->menu = View::factory('pages/menu')->set('menu',$menuData);
我必须怎么做才能让 $this->template->menu 包含视图,这样我才能正确使用它?
我希望这一切都有意义。这是我想做的方式,但也许我完全走错了路。
【问题讨论】:
-
我刚刚在 somePage.php 中找到了问题的答案: $menuBlock = Request::factory('menu/getMenu')->execute(); $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);我希望这对其他人有帮助。
-
另外,不建议在 kohana 中为您的代码使用 __construct() 方法。您应该使用 before()(与 __construct() 相同)和 after()(与 __destruct() 相同)方法。不要忘记也调用 parent::before() :)