もともと PHP には $_SESSION があるので、それを利用すればよいのだが、CakePHP は $this->Session というう形で用意されている。
セッション ? CakePHP Cookbook v2.x documentation
http://book.cakephp.org/2.0/ja/core-libraries/components/sessions.html
残念ながら、$_SESSION と $this->Session と互換性はない模様。他のモジュールとのやり取りをするならば、$_SESSION を使うと良い。
■Model
Model はそのまま
■Controller
sess メソッドで id を保存しておいて、index で検索結果を出すという具合。
in Controller/TestController.php
public function index($id=null) { if ($id==null) { // セッション内のIDを使う $id = $this->Session->read("Test.id"); // session_start(); // $id = $_SESSION['Test.id']; } if (isset($this->params['url']['id'])) $id = $this->params['url']['id']; if ( $id != null ) { $this->set('Test',$this->Test->findAllById($id)); } else { $this->set('Test',$this->Test->find('all')); } }
// セッションを保存 public function sess($id=null) { $this->Session->write("Test.id",$id); // session_start(); // $_SESSION['Test.id'] = $id ; $this->redirect('.'); }
/Test/sess/7 で URL を呼び出すと、/Test/index/7 と同じような呼び出しになる(内部で redirect している)。このときに、sess から index に渡すために $this->Session を使っている。このパターンだと、直接メソッド呼び出しをしたほうが安全か…まあ、URL が /Test/ になるので、それはそれで ok(アドレスが隠蔽化されるという意味で)。
$_SESSION[‘Test.id’] でも同じことができる。残念ながら、$_SESSION[‘Test.id’] と $this->Session->read(“Test.id”); は異なる値を示している。これは名前を「id」とかにしてもダメだった。
■View
View は同じ
■結果
/Test/sess/7 で呼び出すと、$this->Session に保存されて index で参照される。