動作環境が結構古くて2.5.6なので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();
}
}