【问题标题】:Instantiating Request in Controller in Kohana 3.3在 Kohana 3.3 中的控制器中实例化请求
【发布时间】:2012-12-10 19:12:29
【问题描述】:

在升级我自己的模块以使用最新的 Kohana (3.3) 时,我在我的场景中发现了故障。我在我的应用程序中使用模板驱动模式(我的控制器扩展了 Controller_Theme)。但是对于 AJAX 调用,我在 3.2 版中使用了单独的控制器,它只扩展了控制器。我必须在此控制器中实例化 Request 对象,以便通过 Rquest 对象中的 POST 或 GET 访问传递的变量。我在 __construct() 方法中做到了:

class Controller_Ajax extends Controller {

    public function __construct()
    {       
        $this->request = Request::current();    
    }

    public function action_myaction()
    {
        if($this->is_ajax())
        {
            $url = $this->request->post('url');
            $text = $this->request->post('text');
        }   
    }
}

在 myaction() 方法中,我可以像这样访问已发布的变量。 但这在 Kohana 3.3 中不再起作用。我总是收到这个错误:

ErrorException [ Fatal Error ]: Call to a member function action() on a non-object
SYSPATH/classes/Kohana/Controller.php [ 73 ]
68  {
69      // Execute the "before action" method
70      $this->before();
71      
72      // Determine the action to use
73      $action = 'action_'.$this->request->action();
74 
75      // If the action doesn't exist, it's a 404
76      if ( ! method_exists($this, $action))
77      {
78          throw HTTP_Exception::factory(404,

我确定我的路线设置正确。我没有发现从 3.2 到 3.3 的迁移文档中关于 Request 对象的任何更改。还是我错过了什么?

【问题讨论】:

  • $this->request = Request::current(); - 为什么需要这样做?它应该由框架自动完成,我认为不能保证Request::current 在这个阶段(在构造函数中)可用。否则,如果你真的必须这样做,请尝试将其放入public function before() {}
  • __construct() 方法 - 这就是问题所在。当它停留在我的控制器中时,不会构造请求对象。当我用你提到的before() 方法替换它时,一切都是正确的。是的,$this->req = Request::current() 可以省略。非常感谢!

标签: request kohana kohana-3.3


【解决方案1】:

默认情况下,请求和响应都在Controller 类中初始化(参见下面的代码),因此不需要覆盖它的构造函数。尝试删除你的构造函数,如果这没有帮助,那么你的路由就搞砸了。

abstract class Kohana_Controller {

    /**
     * @var  Request  Request that created the controller
     */
    public $request;

    /**
     * @var  Response The response that will be returned from controller
     */
    public $response;

    /**
     * Creates a new controller instance. Each controller must be constructed
     * with the request object that created it.
     *
     * @param   Request   $request  Request that created the controller
     * @param   Response  $response The request's response
     * @return  void
     */
    public function __construct(Request $request, Response $response)
    {
        // Assign the request to the controller
        $this->request = $request;

        // Assign a response to the controller
        $this->response = $response;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2014-10-15
    • 1970-01-01
    相关资源
    最近更新 更多