DEV Community

Discussion on: Managing the Cart Storage | Building a Shopping Cart with Symfony

 
qferrer profile image
Quentin Ferrer

What version of Symfony are you using?

Thread Thread
 
antoine__ profile image
AntoineChatry

Symfony 6.0

Thread Thread
 
qferrer profile image
Quentin Ferrer • Edited

This tutorial was written with Symfony 5 and it's not compatible with version 6 at this time. In Symfony 6, the Session service has been removed. To get the Session, you now need to inject the RequestStack service and use the new getSession() method.

You need to upgrade the CartSessionStorage like that :

namespace App\Storage;

use App\Entity\Order;
use App\Repository\OrderRepository;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Class CartSessionStorage
 * @package App\Storage
 */
class CartSessionStorage
{
    /**
     * @var RequestStack
     */
    private $requestStack;

    /**
     * The cart repository.
     *
     * @var OrderRepository
     */
    private $cartRepository;

    /**
     * @var string
     */
    const CART_KEY_NAME = 'cart_id';

    /**
     * CartSessionStorage constructor.
     *
     * @param RequestStack $requestStack
     * @param OrderRepository $cartRepository
     */
    public function __construct(RequestStack $requestStack, OrderRepository $cartRepository)
    {
        $this->requestStack = $requestStack;
        $this->cartRepository = $cartRepository;
    }

    /**
     * Gets the cart in session.
     *
     * @return Order|null
     */
    public function getCart(): ?Order
    {
        return $this->cartRepository->findOneBy([
            'id' => $this->getCartId(),
            'status' => Order::STATUS_CART
        ]);
    }

    /**
     * Sets the cart in session.
     *
     * @param Order $cart
     */
    public function setCart(Order $cart): void
    {
        $this->requestStack->getSession()->set(self::CART_KEY_NAME, $cart->getId());
    }

    /**
     * Returns the cart id.
     *
     * @return int|null
     */
    private function getCartId(): ?int
    {
        return $this->requestStack->getSession()->get(self::CART_KEY_NAME);
    }
}
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
antoine__ profile image
AntoineChatry

It worked! It seems that everything is good now.
Thanks!