Symfony购物车数量

时间:2020-06-30 14:59:34

标签: php symfony

我一直在尝试在symfony 5上构建购物车系统,到目前为止,一切正常,除非将产品添加到购物车中,您可以无限次地这样做,即使产品数量为3,您可以刷新页面并将该产品的3个副本添加到购物车中,它将继续添加它们。

我的控制器:

    /**
     * @Route("/meal/{id}", name="meal")
     */
    public function showMeal(Request $request, FormFactoryInterface $formFactory, EventDispatcherInterface $dispatcherInterface)
    {
        $meal = $this->mealService->getMeal($request->get('id'));

        $form = $formFactory->create(MealType::class, null, [
            "meal" => $meal
        ]);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {

            $data = $form->getData();

            $dispatcher = new MealEvent($meal);
            $this->cartService->addMeal($meal, $data['quantity']);

            $dispatcher->dispatch(MealEvent::MEAL_ADDED, new MealEvent($meal, $data['quantity']));

            return $this->redirectToRoute("homepage");
        }


        return $this->render('meal.html.twig', [
            "meal" => $meal,
            "form" => $form->createView()
        ]);
    }

购物服务和餐饮服务

<?php

namespace App\Service;


use App\Model\Meal;
use Symfony\Component\HttpFoundation\Session\SessionInterface;

class CartService
{
    protected $session;
    protected $taxRate = 20;

    public function __construct(SessionInterface $session)
    {
        $this->session = $session;

        if ($this->session->get('cart') === null) {
            $this->session->set('cart', array());
        }
    }

    public function addMeal(Meal $meal, $quantity = 1)
    {
        $cart = $this->session->get('cart');

        $product = array(
            'meal' => $meal,
            'quantity' => $quantity,
            'price' => $meal->getPrice()
        );

        if(array_key_exists($meal->getId(), $cart)){
            $product['quantity'] +=  $cart[$meal->getId()]['quantity'];
        }

        $cart[$meal->getId()] = $product;

        $this->session->set('cart', $cart);
    }

    public function getCartContent(){
        return $this->session->get('cart');
    }

    public function getTotal(){
        $cart = $this->session->get('cart');
        $total = 0;
        foreach ($cart as $meal) {
            $total += $meal['meal']->getPrice() * $meal['quantity'];
        };
        return $total;
    }

    public function emptyCart(){
        $this->session->set('cart', array());
    }

    public function isEmpty(){
        if(empty($this->session->get('cart'))){
            return true;
        }

        return false;
    }

    public function removeMeal(Meal $meal){
        $cart = $this->session->get('cart');

        if($this->getMeal($meal->getId())){

            unset($cart[$meal->getId()]);
            $this->session->set('cart', $cart);

        }
    }

    public function getMeal($id){
        $cart = $this->session->get('cart');

        if(array_key_exists($id, $cart)){
            return $cart[$id]['meal'];
        }else{
            return null;
        }
    }

    public function getTax()
    {
        return $this->getTotal() * $this->taxRate / 100;
    }

    public function countProducts()
    {
        $cart = $this->session->get('cart');
        $count = 0;
        foreach ($cart as $meal) {
            $count += $meal['quantity'];
        };
        return $count;
    }
}


namespace App\Service;


use App\Model\Meal;
use Doctrine\DBAL\Connection;

class MealService
{
    public function __construct(Connection $database)
    {
        $this->database = $database;
    }

    public function getAll()
    {
        return $this->database->fetchAll(
            "SELECT * FROM meal"
        );
    }

    public function getMeal($id)
    {
        $meal = $this->database->fetchAssoc(
            "SELECT * FROM meal WHERE id = ?",
            array($id)
        );

        return new Meal($meal['id'], $meal['name'], $meal['sale_price'], $meal['photo'], $meal['quantity_in_stock'], $meal['description']);
    }
}

event / MealEvent.php

<?php

namespace App\Event;


use App\Model\Meal;
use Symfony\Contracts\EventDispatcher\Event;

class MealEvent extends Event
{


    const MEAL_ADDED = "meal.added";
    const MEAL_DELETED = "meal.deleted";

    private $meal;
    private $quantity;

    public function __construct(Meal $meal, $quantity = 0)
    {
        $this->meal = $meal;
        $this->quantity = $quantity;
    }

    public function getMeal()
    {
        return $this->meal;
    }

    public function getQuantity()
    {
        return $this->quantity;
    }

    public function dispatch(string $MEAL_ADDED, MealEvent $param)
    {
    }
}

我希望这已经足够清楚了,如果您还有其他需要,请告诉我。非常感谢您的帮助!

0 个答案:

没有答案