2012-12-10 43 views
0

在升級我自己的模塊以使用最新的Kohana(3.3)時,我在我的場景中發現了故障。我在我的應用程序中使用模板驅動模式(我的控制器擴展Controller_Theme)。但是對於我在3.2版本中使用的AJAX調用,它只是擴展了Controller。我必須在此控制器中實例化Request對象,以通過POST或GET Rquest對象訪問傳遞的變量。我在__construct()方法中做了:在Kohana中實例化控制器中的請求3.3

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對象的任何更改。還是我錯過了什麼?

+0

'$ this-> request = Request :: current();' - 爲什麼你需要這樣做?它應該由框架自動完成,並且我不認爲在這個階段(在構造函數中)'Request :: current'是可用的。否則,如果你真的必須這樣做,試着把它放在'public function before(){}' –

+0

'__construct()'方法中 - 這是問題所在。當它留在我的Controller中時,Request對象不會被構造。當我像前面提到的那樣用'before()'方法替換它時,一切都是正確的。是的,'$ this-> req = Request :: current()'可以省略。非常感謝! – leosek

回答

0

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; 
    } 
相關問題