如何在symfony 2中管理一个简单的cart会话


how to manage a simple cart session in symfony 2?

im试图在symfony2中制作一个简单的cart,但关于会话的文档非常有限,我找到的唯一例子是关于用户的。

根据我在观看视频时的理解,必须采取以下步骤:

1-确保有一个会话数组,如果没有声明新的会话数组2-通过array_push()将变量添加到会话数组;三显示会话

到目前为止,这是我的代码:

public function sessiontestAction(Request $request)
{  
$session = $request->getSession();
if(!$session)
{
   $session->set('producto');  
}
 $em = $this->getDoctrine()->getManager();
  $producto = $em->getRepository('savaInventarioBundle:TblProductos')->find(29);
     if(!$producto){
         throw $this->createNotFoundException('no se encontro el producto');
     }
     array_push($session, $producto);
  return $this->render('savaInventarioBundle:Catalogo:sessiontest.html.twig',
           array('productos'=> $session));
}

每次调用函数时,我的输出只抛出1个乘积,而不是一个以上,它还显示了以下错误"Warning:array_push()expects parameter 1 to be array,object giving i"

所以经过一些测试,我解决了我的问题。如果您想在symfony 2中使用array_push()来管理会话,可以这样做。

symfony2管理会话,而不应该使用$_session,这就是我在会话中推送数组的方式。

公共函数sessiontestAction(Request$Request){

    $productos = array();
   // $session = $request->getSession();
    $session = $this->getRequest()->getSession();
    //check if the session have products
    if ($session->has('producto')) {
        $productos = $session->get('producto');
        array_push($productos, "tomate", "lechuga");
        $session->set('producto', $productos);
    } //if it doesnt create the session and push a array for testing
    else{
        $test = array("orange", "banana");
        $session->set('producto', $test);
    }

//为了从会话传递一个数组,必须将其设置在一个新数组上。$productos=$session->get('producto');return$this->render('savaInventarioBundle:Catalogo:sessiontest.html.trick',array('productos'=>$productos));}

$request->getSession()返回一个对象(实现SessionInterface的Session实例),array_push函数接收一个数组作为第一个参数(array_push (array &$array , mixed $value1 [, mixed $... ])),当然这里不能使用array_ppush函数。

我认为解决方案将是创建一个数组,将此数组设置为会话,第二次从会话中检索它修改它并将其存储回会话,例如:

$session = $request->getSession();
$myArray = array(
    FIRST_ELEMENT
);
$session->set('cartElements', $myArray);
....
$cartElements = $session->get('cartElements');
array_push($cartElements, 'SECOND_ELEMENT');
$session->set('cartElements', $cartElements);
....

获取如下会话:$session=$request->getSession();

并设置会话中的参数如下:$session->set('session_var_name',$var);

并在会话中获取如下参数:$request->get('session_var_name');

我希望这对你有帮助!