在SilverStripe中取消设置会话

nic*_*iel 5 session silverstripe

我正在SilverStripe建立一个非常简单的在线商店.我正在写一个功能,从购物车中删除一个项目(order在我的情况下).

我的设置:

我的端点将JSON返回到视图以便在ajax中使用.

public function remove() {

    // Get existing order from SESSION
    $sessionOrder = Session::get('order');

    // Get the product id from POST
    $productId = $_POST['product'];

    // Remove the product from order object
    unset($sessionOrder[$productId]);

    // Set the order session value to the updated order
    Session::set('order', $sessionOrder);

    // Save the session (don't think this is needed, but thought I would try)
    Session::save();

    // Return object to view
    return json_encode(Session::get('order'));
}
Run Code Online (Sandbox Code Playgroud)

我的问题:

当我将数据发布到此路由时,产品将被删除但只是暂时删除,然后下次调用remove时,前一项将返回.

例:

订单对象:

{
  product-1: {
    name: 'Product One'
  },
  product-2: {
    name: 'Product Two'
  }
}
Run Code Online (Sandbox Code Playgroud)

当我发布删除时,product-1我得到以下内容:

{
  product-2: {
    name: 'Product Two'
  }
}
Run Code Online (Sandbox Code Playgroud)

哪个似乎有效,但后来我尝试删除product-2并得到这个:

{
  product-1: {
    name: 'Product One'
  }
}
Run Code Online (Sandbox Code Playgroud)

AB的SON回来了!当我检索整个购物车时,它仍包含两者.

我如何order坚持下去?

小智 3

您的期望是正确的,它应该适用于您编写的代码。但是,管理会话数据的方式不适用于删除数据,因为它不被视为状态更改。只有正在编辑的现有数据才会被视为如此。如果您想了解更多信息,请参阅 Session::recursivelyApply()。我知道的唯一方法是(不幸的是)在设置“order”的新值之前直接强调 textmanipulate $_SESSION

public function remove() {

  // Get existing order from SESSION
  $sessionOrder = Session::get('order');

  // Get the product id from POST
  $productId = $_POST['product'];

  // Remove the product from order object
  unset($sessionOrder[$productId]);
  if (isset($_SESSION['order'])){
    unset($_SESSION['order']);
  }
  // Set the order session value to the updated order
  Session::set('order', $sessionOrder);

  // Return object to view
  return json_encode(Session::get('order'));
}
Run Code Online (Sandbox Code Playgroud)