【问题标题】:CakePhp3 redirect from private methodCakePhp3 从私有方法重定向
【发布时间】:2018-09-07 10:45:09
【问题描述】:

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;

   }

}

我的问题是:

我应该用什么代码代替

/* 重定向到失败的 URL */

将用户重定向到不同的 url?

使用:

return $this->redirect($url);

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

【问题讨论】:

  • $this->redirect() 在 CakePHP 3.6 $this->initData() 中为我工作。
  • 它不起作用,因为在 initData 中 return $this->redirect($url) 只会返回一个响应对象到 myAction1、myAction2 等。它可以从 myAction1、myAction2 内部调用它,等等,但我必须全部更改,这就是我要避免的。

标签: redirect cakephp controller


【解决方案1】:

(目前)还没有内置支持。自己实现它应该足够简单,例如,您可以覆盖 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
        );
    }
}

【讨论】:

  • 谢谢。没那么简单,但我会试试看。
猜你喜欢
  • 1970-01-01
  • 2015-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-07
  • 1970-01-01
  • 2017-02-23
  • 1970-01-01
相关资源
最近更新 更多