CakePHP3 - 未保留 Cookie 值



我有一个问题,如果使用 CakePHP3 切换到不同的部分(控制器(,我设置的 cookie 的值没有被保留。

我在应用程序控制器中建立了原始cookie,因此它是全站点的:

<?php
namespace AppController;
use CakeControllerController;
use CakeEventEvent;
use CakeHttpCookieCookie;
use CakeHttpCookieCookieCollection;
class AppController extends Controller
{
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Cookie');
//set up initial cart cookie
$this->response = $this->response->withCookie(
(new Cookie('cart'))
->withPath('/')
->withValue(json_encode([]))
->withExpiry(new DateTime('+1 month'))
);
}

然后,我在购物车控制器中设置它以将所选项目添加到购物车cookie中:

<?php
// src/Controller/CartController.php
namespace AppController;
use CakeI18nTime;
use CakeHttpCookieCookie;
use CakeHttpCookieCookieCollection;
class CartController extends AppController 
{
public function index()
{
$cart = json_decode($this->request->getCookie('cart'));
$add_cart = ($this->request->getQuery('add') == null ? [] : $this->request->getQuery('add'));
if (count($add_cart) > 0) {
foreach($add_cart as $ac) {
if(!in_array($ac, $cart)) {
$cart[] = $ac;
}
}
}
//replace cookie
$this->response = $this->response->withCookie(
(new Cookie('cart'))
->withPath('/')
->withValue(json_encode($cart))
->withExpiry(new DateTime('+1 month'))
);
$this->loadModel('Books');
$cart_items = [];
foreach($cart as $cartp) { //'contain' => ['BookTypes'], 
$book = $this->Books->get($cartp, ['fields' => array('id','name','description')]);
$cart_items[] = $book;
}
$this->set(compact('cart_items'));
}

如果我停留在"购物车"内,cookie 会保留该值。 但是,一旦我移动到任何其他页面(主页或浏览书籍(,cookie 值就会重置为空(空数组(。

是什么原因造成的?

我发现了我的问题。

不得不将最初的cookie从initialize()移动到AppController中的beforeFilter().php现在它似乎正在工作。

最新更新