Help us understand the problem. What is going on with this article?

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

普段は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());
        }
    }
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした