LoginSignup
0
0

More than 5 years have passed since last update.

【CakePHP】リダイレクト先を動的に設定する

Posted at

動作環境が結構古くて2.5.6なので3系でもそのままいけるかは不明です。

  1. メルマガ等にコンテンツのリンクを貼る
  2. 未ログインの場合はログイン画面に飛ばす
  3. ログイン完了後にコンテンツに飛ばす

といった動きをしたい時なんかに使えます。

1. リダイレクトURL(パス)を保存するfunctionを用意

親クラス(AppControllerとか)に実装すると良さげです。

AppController.php
private function storeRedirectPath() {
  // このパスは保存しない
  $exclude = ['/login', '/aaa', '/bbb'];
  $currentPath = Router::url();
  if (!in_array($currentPath, $allow)) {
      $this->Auth->redirectUrl($currentPath);
  }
}

2. 1.のfunctionを呼び出す処理を追加

このへん

AppController.php
public function beforeFilter()
{
  $this->storeRedirectPath();
}

あるいは

AppController.php
public function beforeRender()
{
  $this->storeRedirectPath();
}

※この辺のfunctionは初期表示時以外にも呼ばれるので確認してからの方が良いです。

3. 保存したパスにリダイレクトする処理を追加

AppController.php
protected function redirectToStoredPath() {
  $this->redirect($this->Auth->redirectUrl());
}
LoginController.php
public function index()
{
  // ログイン済みの場合はリダイレクト
  if ($this->Auth->login()) {
    $this->redirectToStoredPath();
  }
}
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