我在 Kohana 3.1.3.1 中的 HMVC 子请求后保留变量的值时遇到问题,我想知道如何最好地处理/修复它。我以为 Kohana 中的附加请求是相互隔离的,但似乎并非如此......
首先,我创建了一个控制器来扩展 Controller_Template:
abstract class Controller_Website extends Controller_Template {
public $page_info;
public $allow_caching;
public function before()
{
// ... more unrelated code here ...
// Only do this if auto_render is TRUE (default)
if ($this->auto_render === TRUE AND $this->request->is_initial())
{
// Set our Page_Info to the values we just loaded from the database
$this->page_info = clone $this->navs[$slug];
}
// ... more unrelated code here ...
}
public function after()
{
// ... more unrelated code here ...
// For internal requests, let's just get everything except for the template
if (! $this->request->is_initial())
{
$this->response->body($this->template->main_view->render());
}
// Only if auto_render is still TRUE (Default)
if ($this->auto_render === TRUE AND $this->request->is_initial())
{
// ... more unrelated code here ...
// ... get stuff from the database to populate the template ...
// now render the response body
$this->response->body($this->template->render());
}
// ... more unrelated code here...
// including setting headers to disable/enable caching
}
}
这是其中一个控制器的外观示例:
class Controller_Events extends Controller_Website {
public function action_filtered()
{
// ... do some stuff ...
// and set some values
$this->page_info->page_title = 'Set in Events controller';
// and some more stuff including generating some output
}
}
现在我希望我的其他控制器之一能够在没有模板的情况下从事件控制器中提取输出。Controller_Website(上图)负责从输出中排除模板,但考虑一下:
class Controller_Search extends Controller_Website {
public function action_index()
{
// ... do some stuff ...
// now let's include the result from our events controller
$this->template->main_view->events = Request::factory()
->controller('events')
->action('filtered')
->execute();
// and set some values
$this->page_info->page_title = 'Set in Search controller';
// and some more stuff including generating some output
}
}
因此,当我的模板调用时echo $this->page_info->page_title;
(请记住,我的模板仅包含在搜索控制器的输出中,而不是事件控制器的输出中),我希望它返回“在搜索控制器中设置”,而是返回“在事件控制器中设置”
问题是这个action_filtered()
方法很长,我设置了几个路由使用这个方法来输出几个事件页面(比如按年、月、地点、城市等过滤事件)所以它没有意义在我的搜索控制器中复制此方法。因此需要 HMVC 请求。当过滤的操作被称为主/初始请求时,设置值是有意义的,$page_info
但是当它被称为子请求时,我需要保留在搜索控制器中设置的值,或者任何初始控制器。
当然,我可以在事件控制器中创建一个 if 语句,仅在主请求时更新这些值,但这显然不太理想。一定有办法让这个子请求与初始请求隔离开来吗?
我做错了什么,或者解决这个问题的最佳方法是什么?
提前致谢!
DM