在CakePHP 3.8中,我的控制器段如下所示:
// ...
public function beforeFilter(Event $event)
{
// ...
$this->Cookie->configKey('guestCookie', [
'expires' => '+1 days',
'httpOnly' => true,
'encryption' => false
]);
if(!$this->Cookie->check('guestCookie')) {
$guestID = Text::uuid();
$this->Cookie->write('guestCookie', $guestID);
}
$this->guestCookie = $this->Cookie->read('guestCookie');
// ...
}
public function error()
{
// ...
$this->Cookie->delete('guestCookie');
// ...
}
// ...
如何在CakePHP4版本中编写相同的东西?我的问题与定义Cookie有关。Cookie设置说明如下:https://book.cakephp.org/4/en/controllers/request-response.html#cookie-集合,但不幸的是,这对我没有任何帮助。
我试图用这种方式解决问题:
public function beforeFilter(EventInterface $event)
{
//...
if(!$this->cookies->has('guestCookie')) {
$cookie = (new Cookie('guestCookie'))->withValue(Text::uuid())->withExpiry(new DateTime('+20 days'))->withPath('/')->withSecure(false)->withHttpOnly(true);
$this->cookies = new CookieCollection([$cookie]);
}
$this->guestCookie = $this->cookies->get('guestCookie')->getValue();
//...
}
在我的情况下$this->cookie->has('guestCookie'(总是'false'。cookie值从未存储在浏览器中。请帮忙。
很少需要接触cookie集合,大多数时候只需要简单地从请求对象读取cookie值,并将cookie写入响应对象,所以我建议您坚持这样做,直到真正需要集合为止。
在解释何时使用什么方面,文档可能会做得更好。
读取、写入和删除cookie
如链接文档中所示,cookie值可以通过以下方式读取:
$this->request->getCookie($cookieName)
并通过写入
$this->response = $this->response->withCookie($cookieObject)
重新分配响应对象很重要(除非您直接从控制器返回它(,因为它是不可变的,这意味着withCookie()
将返回一个新的响应对象,而不是修改当前的响应对象。
删除cookie可以通过使用过期cookie进行响应,使用withExpiredCookie()
而不是withCookie()
,或者通过$cookie->withExpired()
获取cookie的过期版本并将其传递给withCookie()
来完成。
配置cookie默认值
如果您愿意,可以通过Cookie::setDefaults()
:设置cookie默认值
CakeCookieCookie::setDefaults([
'expires' => new DateTime('+1 days'),
'http' => true,
]);
然而,这将在应用程序范围内应用于在此之后创建的所有cookie实例,因此您可能很少使用它,如果使用它,请小心!
从Cookie组件移植
使用新的API,您的代码可以这样编写,$this->guestCookie
保存cookie值,可以是新生成的值,也可以是从应用程序接收的cookie中获得的值:
use CakeHttpCookieCookie;
// ...
public function beforeFilter(Event $event)
{
// ...
$guestID = $this->request->getCookie('guestCookie');
if(!$guestID) {
$guestID = Text::uuid();
$cookie = Cookie::create('guestCookie', $guestID, [
'expires' => new DateTime('+1 days'),
'http' => true,
]);
$this->response = $this->response->withCookie($cookie);
}
$this->guestCookie = $guestID;
// ...
}
public function error()
{
// ...
$cookie = new Cookie('guestCookie');
$this->response = $this->response->withExpiredCookie($cookie);
// ...
}
// ...
另请参阅
- 食谱>请求&响应对象>请求>Cookie
- 食谱>请求&响应对象>响应>设置Cookie