-3

I am trying to use sessions in Symfony version 5.3.9 with RequestStack because SessionInterface is deprecated. I get the following error:

Cannot use object of type Symfony\Component\HttpFoundation\Session\Session as array

here: if(isset($cart[$id])){ (in my addToCart function) in symfony 5.2 it was ok

Thank you for your help

My CartController.php :

    <?php

namespace App\Controller;

use App\Services\CartServices;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class CartController extends AbstractController
{
    /**
     * @Route("/cart", name="cart")
     */
    public function index(CartServices $cartServices): Response
    {
        $cartServices->addToCart(3);
        dd($cartServices->getCart());
        return $this->render('cart/index.html.twig', [
            'controller_name' => 'CartController',

        ]);
    }
}

My CartServices.php :

    <?php

namespace App\Services;

use App\Repository\ProductRepository;
use Symfony\Component\HttpFoundation\RequestStack;

class CartServices
{
    private $requestStack;
    private $repoProduct;

    public function __construct(RequestStack $requestStack, ProductRepository $repoProduct)
    {
        $this->requestStack = $requestStack;
        $this->repoProduct = $repoProduct;
    }
    
    public function addToCart($id){
        $cart = $this->getCart();
        if(isset($cart[$id])){
            $cart[$id]++;
        }else{
            $cart[$id] = 1;
        }
        $this->updateCart($cart);
    }

$cart = $this->getCart():

    public function getCart(){
        return $this->requestStack->getSession('cart', []);
    }

Thank you very much but I still have no results

result of the cart session

My CartServices.php

<?php

namespace App\Services;

use App\Repository\ProductRepository;
use Symfony\Component\HttpFoundation\RequestStack;

class CartServices
{
    private $requestStack;
    private $repoProduct;

    public function __construct(RequestStack $requestStack, ProductRepository $repoProduct)
    {
        $this->requestStack = $requestStack;
        $this->repoProduct = $repoProduct;
    }
    
    public function addToCart($id){
        $cart = $this->getCart();
        if(isset($cart[$id])){
            //produit déjà dans le panier on incrémente
            $cart[$id]++;
        }else{
            //produit pas encore dans le panier on ajoute
            $cart[$id] = 1;
        }
        $this->updateCart($cart);
    }

    public function deleteFromCart($id){
        $cart = $this->getCart();
        //si produit déjà dans le panier 
        if(isset($cart[$id])){
            //si il y a plus d'une fois le produit dans le panier on décrémente
            if($cart[$id] >1){
                $cart[$id] --;
            }else{
                //Sinon on supprime
                unset($cart[$id]);
            }
            //on met à jour la session
            $this->updateCart($cart);
        }
    }

    public function deleteAllToCart($id){
        $cart = $this->getCart();
        //si produit(s) déjà dans le panier 
        if(isset($cart[$id])){
                //on supprime
                unset($cart[$id]);
            }
            //on met à jour la session
            $this->updateCart($cart);
    }

    public function deleteCart(){
        //on supprime tous les produits (on vide le panier)
        $this->updateCart([]);
    }

    public function updateCart($cart){
        $this->requestStack->getSession('cart', $cart);
    }

    public function getCart(){
        $session = $this->requestStack->getSession();
        return $session->get('cart', []);
    }

    public function getFullCart(){
        $cart = $this->getCart();
        $fullCart = [];
        foreach ($cart as $id => $quantity){
            $product = $this->repoProduct->find($id);
            if($product){
                 //produit récupéré avec succés
                 $fullCart[]=[
                    'quantity' => $quantity,
                    'product' => $product
                ];
            }else{
                //id incorrect
                $this->deleteFromCart($id); //on ne met pas à jour la session car cette method le fait aussi (voir plus haut dans la fonction deleteFromCart)
            }
        }
    }

}

My CartController.php

<?php

namespace App\Controller;

use App\Services\CartServices;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Session\SessionInterface;


class CartController extends AbstractController
{
    /**
     * @Route("/cart/add/{id}")
     */
    public function addToCart($id,CartServices $cartServices):Response
    {
        $cartServices->addToCart($id);
        dd($cartServices->getCart(1));
        return $this->render('cart/index.html.twig', [
            'controller_name' => 'CartController',

        ]);
    }
}
TBA
  • 49
  • 5
  • can you show the code of the method getCart() ? we don't see on your code something that use session –  Oct 22 '21 at 13:52
  • What have you tried to resolve the problem? Where are you stuck? What kind of object is `$cart`? – Nico Haase Oct 22 '21 at 15:35

2 Answers2

0
    public function getCart(){
        return $this->requestStack->getSession('cart', []);
    }
TBA
  • 49
  • 5
  • 1
    Just for info, there is an edit button you can use to update your question with additional info. And ask yourself what sort of result do you expect from $session('cart',[])? – Cerad Oct 22 '21 at 15:17
  • Unless this is an answer to the given question (which would definitiely need some more details, such that others can learn from it), please add it to your question by editing – Nico Haase Oct 22 '21 at 15:34
0

the method getSession of RequestStack return an object of SessionInterface, so your code is not correct, bellew the body of the method :

    /**
     * Gets the current session.
     *
     * @throws SessionNotFoundException
     */
    public function getSession(): SessionInterface
    {
        if ((null !== $request = end($this->requests) ?: null) && $request->hasSession()) {
            return $request->getSession();
        }

        throw new SessionNotFoundException();
    }

So, you should update your method getCart like this :

    public function getCart(){
        $session =  $this->requestStack->getSession();

        return $session->get('cart', []);
    }
Abdelhak ouaddi
  • 474
  • 2
  • 4