2015-07-11 72 views
0

在我的CakePHP 3應用程序,一個控制器重定向後,我得到這個錯誤:CakePHP的3重定向器

Error: [LogicException] Controller action can only return an instance of Response 
Request URL: /mycontroller/ 
Stack Trace: 
#0 /var/www/vhosts/example.com/httpdocs/vendor/cakephp/cakephp/src/Routing/Dispatcher.php(87): Cake\Routing\Dispatcher->_invoke(Object(App\Controller\SigninsController)) 
#1 /var/www/vhosts/example.com/httpdocs/webroot/index.php(37): Cake\Routing\Dispatcher->dispatch(Object(Cake\Network\Request), Object(Cake\Network\Response)) 
#2 {main} 

關於把CakePHP 2 controller documentation重定向是這樣的:

$this->redirect('/orders/thanks'); 
$this->redirect('http://www.example.com'); 
return $this->redirect(
     array('controller' => 'orders', 'action' => 'confirm') 
    ); 

但在CakePHP中3 documentation似乎是這樣的:

return $this->redirect('/orders/thanks'); 
return $this->redirect('http://www.example.com'); 
return $this->redirect(
      ['controller' => 'Orders', 'action' => 'thanks'] 
     ); 

當我添加在$this->redirect之前3210字,錯誤得到解決。這是否會造成問題?因爲我看不到cakephp 3 migration guide中的返回重定向部分。遷移指南只提到第三個參數被刪除。

+1

引用[遷移指南](http://book.cakephp.org/3.0/en/appendices/3-0-migration-guide.html#id2):「該方法不能再發送響應並退出腳本,而是返回一個帶有適當頭文件的Response實例。「 – ADmad

回答

0

看看CakePHP中的3個應用程序this

Response provides an interface to wrap the common response-related tasks such as: Sending headers for redirects.

this

You should return the response instance from your action to prevent view rendering and let the dispatcher handle actual redirection.

2

返回時使用要重定向到其他網頁,或者我們可以說,其他控制器的動作/方法或者即使您想重定向到第三方鏈接(如您已指定): -

return $this->redirect('/orders/thanks'); 
return $this->redirect('http://www.example.com'); 
return $this->redirect(['controller' => 'Orders', 'action' => 'thanks']); 

如果你想重定向到其他方法在同一個控制器,那麼你可以離開返回並使用setAction如下,但這裏的URL將保持不變。

$this->setAction('thanks'); 

返回是更好的方法,如果您使用下面的代碼,URL將會重定向。

return $this->redirect(['action' => 'thanks']);