CakePhp3从私有方法重定向

问题描述 投票:0回答:1

我有CakePhp3的这个问题:

在我的控制器中,我想做这样的事情:

class MyController extends Controller
{ 

   public function myAction1(){
    $this->initData();
    /* more code here */
   }

   public function myAction2(){
    $this->initData();
    /* more code here */
   }

   public function myAction3(){
    $this->initData();
    /* more code here */
   }

   /* more actions here */


   private function initData(){
    if ($this->validData()){
     /* complex code to initalize data */
    }else{
     /* REDIRECT TO FAIL URL */
    }
   }

   private function validData(){

     /* complex code to validate data */
     return $valid;

   }

}

我的问题是:

我应该使用什么代码而不是

/ * REDIRECT TO FAIL URL * /

将用户重定向到其他网址?

使用:

return $ this-> redirect($ url);

在initData(ofcourse)内部不起作用,我不想在每个动作中处理重定向。

redirect cakephp controller
1个回答
0
投票

(尚未)没有内置支持。它应该很简单,你自己实现这个,你可以例如覆盖Controller::invokeAction()来捕获重定向异常,并使其相应地返回重定向响应,如:

public function invokeAction()
{
    try {
        return parent::invokeAction();
    } catch (\Cake\Routing\Exception\RedirectException $exception) {
        return $this->redirect($exception->getMessage(), $exception->getCode());
    }
}

private function initData()
{
    if ($this->validData()) {
        // ....
    } else {
        throw new \Cake\Routing\Exception\RedirectException(
            \Cake\Routing\Router::url([/* ... */]), // redirect URL
            302 // HTTP status code
        );
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.