2014-09-21 41 views
0

即時嘗試在symfony2中製作一個簡單的購物車,但關於會話的文檔非常有限,我發現的唯一例子是關於用戶的。如何在symfony 2中管理簡單的購物車會話?

從我瞭解的看視頻是必須做出這樣的步驟:

1,確保有一個session數組,如果不申報新的會話陣列 變量session數組通過2個加array_push(); 3顯示會話

這是我到目前爲止的代碼:

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級的產品,而不是一個以上,此外,它顯示了這個錯誤「警告:array_push( )期望參數1是陣列,給定對象i」的

回答

1

$request->getSession()返回一個對象的Session(例如它實現SessionInterface),array_push函數接收數組作爲第一個參數(array_push (array &$array , mixed $value1 [, mixed $... ])),當然也可以不使用array_push函數的在這裏。

我認爲解決方案將創建一個數組,設置該數組會議,第二次retreive從會議回來修改,並將其存放回會話,例如:

$session = $request->getSession(); 

$myArray = array(
    FIRST_ELEMENT 
); 

$session->set('cartElements', $myArray); 

.... 

$cartElements = $session->get('cartElements'); 

array_push($cartElements, 'SECOND_ELEMENT'); 

$session->set('cartElements', $cartElements); 

.... 
0

得到這樣的會議這個:$ session = $ request-> getSession();

並在會話中設置參數,如下所示:$ session-> set('session_var_name',$ var);

並獲取會話中的參數,如下所示:$ request-> get('session_var_name');

我希望這對你有所幫助!

2

所以經過一些測試我解決了我的問題。如果你想用array_push()來管理symfony 2中的會話,你可以這樣做。

symfony2管理會話,你不應該這樣做$ _SESSION,這是我如何推動數組在會話中。

公共職能sessiontestAction(請求$要求){

$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.twig',array('productos'=> $ productos)); }

+0

有什麼區別? – xurshid29 2014-09-30 05:03:18

+0

我問了3件事, 1-確保有一個會話數組,如果沒有聲明一個新的會話數組(你的答案缺少這個) 2通過array_push()添加變量到會話數組; 3-session session symfony以不同的方式管理會話,我不知道session-> has(),並想學習如何管理會話,我已經知道背後的邏輯我想要的,但不知道功能,必須弄清楚這些事情。 – 2one2 2014-10-01 00:39:35