redev

technical miscellaneous memorandum

アクションの呼び出しとリダイレクト

$this->redirect('/hello/index');
などとするとリダイレクトされ、表示されるアドレスも変わる。

一方、表示されるアドレスはそのままで別アクションで処理を行う際は
$this->setAction('err');
などと記述すると実現できる。但し、setActionの後はreturnをつけないと、その後の処理が混じる。


下記の例では/hello/index/abc等でアクセスするとHello!と表示され、
/hello/index/でアクセスするとerr()の内容が表示される。
/hello/dummy/でアクセスすると/hello/index/にリダイレクトされる。

<?php
namespace App\Controller;

use App\Controller\AppController;

class HelloController extends AppController {
    public function index($a = '') {
        if ($a == '' ) {
            $this->setAction('err');
            return; //これを付けないと、これ以降の処理が実行されてしまう
        }
        $this->autoRender = false;
        echo "<h1>Hello!</h1>";
    }
    
    public function dummy() {
        $this->redirect('/hello/index'); //アドレスも変わる
    }
    
    public function err() {
        $this->autoRender = false;
        echo "err dayo!";
    }
}