编辑:
正如@Darsstar 在评论中建议的那样,最好在控制器的 before 方法中更改操作而不是覆盖 execute 方法。所以它是这样的,在你的用户控制器中:
protected $default_action = 'index';
public function before()
{
$action = 'action_'.$this->request->action();
if (!empty($this->default_action) && !method_exists($this, $action))
{
$this->request->action($this->default_action);
}
}
因此,如果没有当前操作并且定义了默认操作,则会将当前请求操作更改为默认操作。您可以将此代码放入主控制器中,并在子控制器中仅定义 $default_action。
旧答案:
您应该覆盖 Controller 类的执行方法。通常它看起来像这样:
public function execute()
{
// Execute the "before action" method
$this->before();
// Determine the action to use
$action = 'action_'.$this->request->action();
// If the action doesn't exist, it's a 404
if ( ! method_exists($this, $action))
{
throw HTTP_Exception::factory(404,
'The requested URL :uri was not found on this server.',
array(':uri' => $this->request->uri())
)->request($this->request);
}
// Execute the action itself
$this->{$action}();
// Execute the "after action" method
$this->after();
// Return the response
return $this->response;
}
把它改成这样:
public function execute()
{
// Execute the "before action" method
$this->before();
// Determine the action to use
$action = 'action_'.$this->request->action();
// If the action doesn't exist, check default action
if ( ! method_exists($this, $action))
{
//Can be hardcoded action_index or $this->default_action set in controller
$action = 'action_index';
// If the action doesn't exist, it's a 404
if ( ! method_exists($this, $action))
{
throw HTTP_Exception::factory(404,
'The requested URL :uri was not found on this server.',
array(':uri' => $this->request->uri())
)->request($this->request);
}
}
// Execute the action itself
$this->{$action}();
// Execute the "after action" method
$this->after();
// Return the response
return $this->response;
}
现在如果动作不存在,它会检查默认动作并运行它,或者如果不存在则抛出 404。