CakePHP3 - 未保留Cookie值

时间:2018-06-14 12:51:59

标签: 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;

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

    }

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

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

如果我留在&#34; Cart&#34;中,cookie会保留该值。但是,只要我移动到任何其他页面(主页或浏览书籍),cookie值就会重置为空(空数组)。

造成这种情况的原因是什么?

1 个答案:

答案 0 :(得分:0)

我发现了我的问题。

必须在AppController.php中将初始cookie从initialize()移动到beforeFilter(),现在它似乎正在运行。