CakePHP 3:创建多维 cookie

CakePHP 3 : creating multidimensional cookie

我正在使用 CakePHP 3.2 构建购物车。

我正在使用 Cookie 组件将产品存储在购物车中。

这就是我将产品添加到购物车的操作

public function addToCart()
    {
      $this->loadModel('Products');

      if ($this->request->is('post')) {
        $p_id = $this->request->data('product_id');
        $p_quantity = $this->request->data('qnty');

        $product = $this->Products->get($p_id);

        if (!$product) {
          throw new NotFoundException(__('Invalid Product'));
        }

          $this->Cookie->write('Cart',
            ['id' => $p_id, 'quantity' => $p_quantity]);

          $itemsCount = count($this->Cookie->read('Cart'));

          $this->Flash->success(__('Product added to cart'));
          return $this->redirect($this->referer());

      }
    }

如何在 Cookie 中添加多维数组,因为购物车可以有多个产品,每个产品都带有多个值。 另外,如何在 cart() 方法的 view 中打印?

我的cart()方法就是这样

public function cart()
    {
      $cart_products = $this->Cookie->read('Cart');

      $this->set('cart_products', $cart_products);
    }

并打印为

foreach($cart_products as $c_product):
  echo $c_product->id.' : '.$c_product->quantity;   // line 45
endforeach;

但这给出了错误

Trying to get property of non-object [ROOT/plugins/ArgoSystems02/src/Template/Orders/cart.ctp, line 45]

您将数组写入 cookie:

$this->Cookie->write('Cart', ['id' => $p_id, 'quantity' => $p_quantity]);

我相信您想要的是将所有产品存储在 cookie 中:

$cart = $this->Cookie->read('Cart') ? $this->Cookie->read('Cart') : [];
$cart[] = $product;
$this->Cookie->write('Cart', $cart)

尝试以下方法

代替方法

$this->Cookie->write('Cart',['id' => $p_id, 'quantity' => $p_quantity]);

进入

$cart = [];
if($this->Cookie->check('Cart')){
    $cart = $this->Cookie->read('Cart');
}
$cart[] = ['id' => $p_id, 'quantity' => $p_quantity];//multiple
$this->Cookie->write('Cart', $cart);

而不是视图

foreach($cart_products as $c_product):
  echo $c_product->id.' : '.$c_product->quantity;   // line 45
endforeach;

进入

foreach($cart_products as $c_product):
  echo $c_product['id'].' : '.$c_product['quantity'];   // line 45
endforeach;