CakePHP3ではSessionComponentが廃止され、Controller内から$this->Sessionを使うことができなくなった。
代わりに$this->request->session()を使用するのだが、毎回$this->request->session()->read('Hoge.hoge');などとしていると面倒なので、すべてのController内から$this->Sessionでセッションを利用できるようにする。
1-1. AppControllerで$this->Sessionを用意する
1-2. Controllerから$this->Sessionを利用する
どのControllerでも$this->Sessionを利用できるようにするため、AppControllerのinitialize()メソッド内で$this->Sessionに$this->request->session()を代入する。
あとはCakePHP2.xと同様、任意のControllerから$this->Sessionを利用するだけ。
代わりに$this->request->session()を使用するのだが、毎回$this->request->session()->read('Hoge.hoge');などとしていると面倒なので、すべてのController内から$this->Sessionでセッションを利用できるようにする。
1-1. AppControllerで$this->Sessionを用意する
1-2. Controllerから$this->Sessionを利用する
1-1. AppControllerで$this->Sessionを用意する
どのControllerでも$this->Sessionを利用できるようにするため、AppControllerのinitialize()メソッド内で$this->Sessionに$this->request->session()を代入する。
class AppController extends Controller { public function initialize() { parent::initialize(); $this->Session = $this->request->session(); } }これでOK。
1-2. Controllerから$this->Sessionを利用する
あとはCakePHP2.xと同様、任意のControllerから$this->Sessionを利用するだけ。
class HogeController extends AppController { public function hogeAction() { // 読み $hoge = $this->Session->read('Hoge.hoge'); // 書き $this->Session->write('Hoge.hoge', 'hoge'); } }
コメント