CakePHP3-未保留Cookie值

CakePHP3-未保留Cookie值,cakephp,cookies,cakephp-3.0,Cakephp,Cookies,Cakephp 3.0,我有一个问题,如果使用CakePHP3切换到另一个部分(控制器),我设置的cookie的值不会被保留 我在AppController中建立了原始cookie,因此它是站点范围的: <?php namespace App\Controller; use Cake\Controller\Controller; use Cake\Event\Event; use Cake\Http\Cookie\Cookie; use Cake\Http\Cookie\CookieCollection;

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

我在AppController中建立了原始cookie,因此它是站点范围的:

<?php

namespace App\Controller;

use Cake\Controller\Controller;
use Cake\Event\Event;
use Cake\Http\Cookie\Cookie;
use Cake\Http\Cookie\CookieCollection;

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从AppController.php中的
initialize()
移动到
beforeFilter()
,现在它似乎可以工作了

<?php

// src/Controller/CartController.php

namespace App\Controller;
use Cake\I18n\Time;
use Cake\Http\Cookie\Cookie;
use Cake\Http\Cookie\CookieCollection;

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'));
}