PHP code example of tourze / order-cart-bundle

1. Go to this page and download the library: Download tourze/order-cart-bundle library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tourze / order-cart-bundle example snippets


// config/bundles.php
return [
    // ...
    Tourze\OrderCartBundle\OrderCartBundle::class => ['all' => true],
];

use Tourze\OrderCartBundle\Interface\CartManagerInterface;
use Tourze\ProductCoreBundle\Entity\Sku;

class CartController
{
    public function __construct(
        private CartManagerInterface $cartManager
    ) {}

    public function addItem(Sku $sku, int $quantity): Response
    {
        $user = $this->getUser();
        
        try {
            $cartItem = $this->cartManager->addItem(
                $user, 
                $sku, 
                $quantity,
                ['note' => 'Gift wrapping requested']
            );
            
            return $this->json(['success' => true]);
        } catch (InvalidSkuException $e) {
            return $this->json(['error' => $e->getMessage()], 400);
        }
    }
}

use Tourze\OrderCartBundle\Interface\CartDataProviderInterface;

class CartViewController
{
    public function __construct(
        private CartDataProviderInterface $cartDataProvider
    ) {}

    public function view(): Response
    {
        $user = $this->getUser();
        
        // Get cart summary
        $summary = $this->cartDataProvider->getCartSummary($user);
        
        // Get all cart items
        $items = $this->cartDataProvider->getCartItems($user);
        
        // Get only selected items
        $selectedItems = $this->cartDataProvider->getSelectedItems($user);
        
        return $this->render('cart/view.html.twig', [
            'summary' => $summary,
            'items' => $items,
        ]);
    }
}

// Update quantity
$this->cartManager->updateQuantity($user, $cartItemId, 5);

// Remove item
$this->cartManager->removeItem($user, $cartItemId);

// Clear entire cart
$deletedCount = $this->cartManager->clearCart($user);

// Update selection state
$this->cartManager->updateSelection($user, $cartItemId, true);

// Batch update selection
$this->cartManager->batchUpdateSelection($user, [1, 2, 3], false);

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Tourze\OrderCartBundle\Event\CartItemAddedEvent;

class CartEventSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            CartItemAddedEvent::class => 'onItemAdded',
        ];
    }

    public function onItemAdded(CartItemAddedEvent $event): void
    {
        $user = $event->getUser();
        $cartItem = $event->getCartItem();
        
        // Send notification, update analytics, etc.
    }
}

use Tourze\OrderCartBundle\Validator\CartItemValidatorInterface;

class MinimumOrderValidator implements CartItemValidatorInterface
{
    public function validate(UserInterface $user, Sku $sku, int $quantity): void
    {
        if ($quantity < 10 && $sku->getCategory() === 'wholesale') {
            throw new InvalidQuantityException('Minimum order is 10 for wholesale items');
        }
    }

    public function supports(Sku $sku): bool
    {
        return $sku->getCategory() === 'wholesale';
    }

    public function getPriority(): int
    {
        return 50;
    }
}

use Tourze\OrderCartBundle\PriceCalculator\PriceCalculatorInterface;

class PromotionPriceCalculator implements PriceCalculatorInterface
{
    public function calculateItemPrice(CartItemDTO $item): int
    {
        $basePrice = $item->getProduct()->getPrice() * $item->getQuantity();
        
        // Apply buy 2 get 1 free
        if ($item->getQuantity() >= 3) {
            $freeItems = intdiv($item->getQuantity(), 3);
            $paidItems = $item->getQuantity() - $freeItems;
            return $item->getProduct()->getPrice() * $paidItems;
        }
        
        return $basePrice;
    }
    
    // ... other methods
}

use Tourze\OrderCartBundle\Decorator\CartDecoratorInterface;

class ShippingCostDecorator implements CartDecoratorInterface
{
    public function decorate(CartSummaryDTO $summary, UserInterface $user): CartSummaryDTO
    {
        // Add shipping cost based on total amount
        $shippingCost = $summary->getTotalAmount() >= 10000 ? 0 : 500;
        
        // Return new DTO with additional data
        return new CartSummaryDTO(
            $summary->getTotalItems(),
            $summary->getSelectedItems(),
            $summary->getSelectedAmount() + $shippingCost,
            $summary->getTotalAmount() + $shippingCost
        );
    }

    public function getPriority(): int
    {
        return 10;
    }
}

use Tourze\OrderCartBundle\Interface\CartDataProviderInterface;
use Tourze\OrderCheckoutBundle\Service\CheckoutService;

class CheckoutController
{
    public function __construct(
        private CartDataProviderInterface $cartDataProvider,
        private CheckoutService $checkoutService
    ) {}

    public function checkout(): Response
    {
        $user = $this->getUser();
        
        // Get selected items for checkout
        $selectedItems = $this->cartDataProvider->getSelectedItems($user);
        
        if (empty($selectedItems)) {
            throw new \LogicException('No items selected for checkout');
        }
        
        // Create order from cart items
        $order = $this->checkoutService->createOrderFromCart($selectedItems);
        
        return $this->redirectToRoute('payment', ['order' => $order->getId()]);
    }
}
bash
# Remove cart items older than 30 days
php bin/console order-cart:clean-expired

# Specify retention period
php bin/console order-cart:clean-expired --days=7

# Dry run mode
php bin/console order-cart:clean-expired --dry-run

# Custom batch size
php bin/console order-cart:clean-expired --batch-size=500