Cookieを使おうと思っていろいろ調べたのだがなんだかわけがわからないのでまとめた。
CakePHP3.7をベースに、過去のバージョンでの仕様をまとめています。
CakePHP3.4以前
$this->loadComponent('Cookie');
// 読み
$this->Cookie->read(key);
// 書き
$this->Cookie->write(key, value);
// 削除
$this->Cookie->delete(key);
CakePHP2系と同様にコンポーネントを使って読み書きしていたが、これは廃止予定。
CakePHP3.5
Cakeの公式ドキュメントで
バージョン 3.5.0 で撤廃: CookieComponent の代わりに クッキー暗号化ミドルウェア を使用してください。
と記述されているが、意味不明。
どうも、クッキーを暗号化する際にはクッキー暗号化ミドルウェア を使えという意味らしいが、とりあえず読み書きする方法を教えてほしいんだよ。
ということでこちら
https://book.cakephp.org/3.0/ja/controllers/request-response.html#response-cookies
// イミュータブル API (3.4.0 以上) を使って配列としてクッキーを追加
$this->response = $this->response->withCookie('remember_me', [
'value' => 'yes',
'path' => '/',
'httpOnly' => true,
'secure' => false,
'expire' => strtotime('+1 year')
]);
// 3.4.0 より前
$this->response->cookie('remember', [
'value' => 'yes',
'path' => '/',
'httpOnly' => true,
'secure' => false,
'expire' => strtotime('+1 year')
]);
レスポンスの中のメソッドを使うようになったらしい。
CakePHP3.7
3.4と同様にwithCookieメソッドを使ってみたんだけど
Cake\Http\Response::withCookie(string $name, array $data) is deprecated. Pass an instance of \Cake\Http\Cookie\Cookie instead. –
うーん。これも廃止予定?でも公式には記載がなくてどうやって書けばいいのかわからん。
ということで、英語版のリファレンスとかあちこち探して見つけたのがこちら
https://book.cakephp.org/3.0/ja/controllers/request-response.html#creating-cookies
英語版の方にはリンクがあったんだけど、日本語版の方にはなかったようです。
でも、これを見てもやっぱり意味不明。
CookieCollectionがなんたらかんたら書いてあるんだけど、意味がさっぱり分かりません。
で、ソースを見たんだけど、読み書きするだけならCookieCollectionはとりあえずどうでもよくて、パラメータを配列で直接渡すのではなく、Cookieオブジェクトを使って渡すようになっただけのようです。
例えばこんな感じです。
use Cake\Http\Cookie\Cookie;
use Cake\I18n\Time;
//クッキーに書き込み設定を作る
//とりあえずデフォルト設定でキーと値だけ渡す
$this->response = $this->response->withCookie(new Cookie('key', 'value'));
//パラメータを渡す場合
$cookie = (new Cookie('key'))
->withValue('1') //value
->withExpiry(new Time('+1 year')) //タイムアウト
->withPath('/')
->withDomain('example.com') //ドメインを指定する場合
->withSecure(false)
->withHttpOnly(true); //HTTPSだけにする
//クッキーの書き込み
$this->response = $this->response->withCookie($cookie);
//取得方法
$this->request->getCookie('key');
//削除方法 これもCookieオブジェクト使わないとdeprecated警告が出ちゃいます。
$this->response = $this->response->withExpiredCookie(new Cookie('key'));
なんだか、公式ドキュメントダメですね…。英語版も書いてなかったので更新が追い付いていないのでしょう。(2019年6月)