LoginSignup
0
0

More than 3 years have passed since last update.

CakePHPでredirect後、即actionを停止する方法

Posted at

普段はaction内でreturn $this->redirect(...)とやるのであまり気になりませんが、
例えば特殊な権限周りを別関数やComponentでチェックして、ダメなら呼び出し先で即redirectで飛ばしてしまいたい場合があります。
(毎回毎回action側で返り値見てif文でredirect...は面倒だし冗長)

その場合、https://github.com/cakephp/cakephp/issues/11197 で提案されている、Exceptionを使う実装が良さそうです。
以下のようなコードをAppController.phpに書いて、redirect()の代わりにredirectWithException()を呼ぶだけで実装できます。

ただし、この場合actinoがその場所で本当に止まるため、DBやファイル編集中に使わないよう注意が必要。
多分afterFilterやbeforeRedirectも動かない。

↓サンプル (上リンクで提案されてる例から少し変更(RedirectExceptionやRouterの場所追加した))

// redirect()の代わりにredirectWithException()を使う
// AppController.phpにコピペでOK。

    public function redirectWithException($url, $status = 302) {
        throw new \Cake\Routing\Exception\RedirectException(\Cake\Routing\Router::url($url, true), $status);
    }

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

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

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

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0