CakePHP 4.1.4-如何在新版本的CakePHP中创建,读取和检查cookie

问题描述

在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版本中编写相同的东西?我的问题与定义Cookies有关。 Cookie设置在此处进行描述: https://book.cakephp.org/4/en/controllers/request-response.html#cookie-collections ,但不幸的是,这根本没有帮助我。

我试图通过这种方式解决问题:

    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-> cookies-> 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的过期版本并将其传递给{{1 }}。

配置cookie默认值

如果需要,可以通过withCookie()设置cookie默认值:

Cookie::setDefaults()

但是,这将在此之后将应用程序范围应用于所有创建的cookie实例,因此您可能很少使用它,如果这样做,请谨慎使用!

从Cookie组件移植

使用新的API,您的代码可以这样编写,其中\Cake\Cookie\Cookie::setDefaults([ 'expires' => new DateTime('+1 days'),'http' => true,]); 保存cookie值,可以是新生成的值,也可以是从应用程序接收到的cookie中获得的值:

$this->guestCookie

另请参见

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...