CakePHPのrender, redirect

Pocket

CakePHPのrenderとredirectのメモ

ViewはView/Examples/index.cptのみ。

class Example extends AppController {

    public function index() {
        $index = 'index : ' . date( 'Y:m:d H:i:s' ); // --- 変数index
        $this->set( 'index', $index );
    }

    public function some() {
        $some = 'some : ' . date( 'Y:m:d H:i:s' );
        $this->Session->setFlash( 'someメッセージ' );
        $this->set( 'some', $some );    // 変数some
        $this->render( 'index' );
    }

    public function other() {
        $other = 'other : ' . date( 'Y:m:d H:i:s' );
        $this->Session->setFlash('otherメッセージ。' );
        $this->set( 'other', $other );  // --- 変数other
        $this->redirect( [ 'controller' => 'example', 'action' => 'index' ] );

    }

    public function complex() {
        if ( true ) {
            $some = 'some : ' . date( 'Y:m:d H:i:s' );
            $this->Session->setFlash( 'someメッセージ' );
            $this->set( 'some', $some );
            $this->render( 'index' );       // --- complexメソッドの処理は終了しない。
        }
        $other = 'other : ' . date( 'Y:m:d H:i:s' );
        $this->Session->setFlash('otherメッセージ。');
        $this->set( 'other', $other );  // --- otherはindexビューで利用できない。
        $this->redirect( [ 'controller' => 'example', 'action' => 'index' ] );
    }
}
  • $this->render( ‘index’ )
    • indexメソッドは実行されない(index.cptでindexメソッドの変数indexは利用できない)。
    • setで設定した変数を引き継ぐ(サンプルの変数someはindex.cptで利用できる)。
    • setFlashで設定したメッセージを引き継ぐ。
  • $this->redirect( [ ‘controller’ => ‘example’, ‘action’ => ‘index’ ] )
    • indexメソッドが実行される(index.cptでindexメソッドの変数indexは利用できる)。
    • setで設定した変数は引き継がない(サンプルの変数otherはindex.cptで利用できない)。
    • setFlashで設定したメッセージは引き継ぐ。

renderメソッドは処理を終了しない。return falseを付けると呼び出し元へ戻る(complexメソッドは終了)。

コメント

No comments yet.

コメントの投稿

改行と段落タグは自動で挿入されます。
メールアドレスは表示されません。