PHPackages                             tourze/order-cart-bundle - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. tourze/order-cart-bundle

ActiveSymfony-bundle[Utility &amp; Helpers](/categories/utility)

tourze/order-cart-bundle
========================

Shopping cart management bundle for e-commerce systems

1.0.1(5mo ago)0632proprietaryPHPPHP ^8.2CI failing

Since Nov 4Pushed 4mo agoCompare

[ Source](https://github.com/tourze/order-cart-bundle)[ Packagist](https://packagist.org/packages/tourze/order-cart-bundle)[ RSS](/packages/tourze-order-cart-bundle/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (2)Dependencies (47)Versions (3)Used By (2)

Order Cart Bundle
=================

[](#order-cart-bundle)

[English](README.md) | [中文](README.zh-CN.md)

A flexible and extensible shopping cart management bundle for Symfony applications.

Features
--------

[](#features)

- **Complete Cart Management**: Add, update, remove items and manage cart selection states
- **Event-Driven Architecture**: All state changes trigger events for easy integration
- **Extensible Design**: Multiple extension points for custom business logic
- **SKU Entity Integration**: Direct integration with `Tourze\ProductCoreBundle\Entity\Sku`
- **Anemic Model Pattern**: Clean separation of entities and business logic
- **High Quality Standards**: PHPStan Level 8, comprehensive test coverage

Installation
------------

[](#installation)

```
composer require tourze/order-cart-bundle
```

Configuration
-------------

[](#configuration)

### 1. Register the Bundle

[](#1-register-the-bundle)

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

### 2. Configure Services

[](#2-configure-services)

The bundle automatically configures all services. You can override them in your application:

```
# config/packages/order_cart.yaml
services:
    # Implement the ProductProviderInterface for your application
    Tourze\OrderCartBundle\Interface\ProductProviderInterface:
        class: App\Service\ProductProvider
```

### 3. Update Database Schema

[](#3-update-database-schema)

```
php bin/console doctrine:schema:update --force
# Or use migrations
php bin/console make:migration
php bin/console doctrine:migrations:migrate
```

Basic Usage
-----------

[](#basic-usage)

### Adding Items to Cart

[](#adding-items-to-cart)

```
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);
        }
    }
}
```

### Retrieving Cart Data

[](#retrieving-cart-data)

```
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,
        ]);
    }
}
```

### Managing Cart Items

[](#managing-cart-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);
```

Events
------

[](#events)

The bundle dispatches the following events:

- `CartItemAddedEvent` - When an item is added to cart
- `CartItemUpdatedEvent` - When item quantity is updated
- `CartItemRemovedEvent` - When an item is removed
- `CartClearedEvent` - When the entire cart is cleared
- `CartSelectionChangedEvent` - When item selection state changes

### Listening to Events

[](#listening-to-events)

```
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.
    }
}
```

Extension Points
----------------

[](#extension-points)

### Custom Validators

[](#custom-validators)

Create custom validation logic for cart items:

```
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;
    }
}
```

### Custom Price Calculator

[](#custom-price-calculator)

Implement custom pricing logic:

```
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
}
```

### Cart Decorators

[](#cart-decorators)

Add additional data to cart summaries:

```
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;
    }
}
```

CLI Commands
------------

[](#cli-commands)

### Clean Expired Cart Items

[](#clean-expired-cart-items)

```
# 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
```

Integration with Order Checkout Bundle
--------------------------------------

[](#integration-with-order-checkout-bundle)

```
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()]);
    }
}
```

Configuration Reference
-----------------------

[](#configuration-reference)

```
# config/packages/order_cart.yaml
order_cart:
    # Maximum items per cart (default: 100)
    max_cart_items: 100

    # Maximum quantity per item (default: 999)
    max_quantity_per_item: 999

    # Cart expiration days for cleanup command (default: 30)
    cart_expiration_days: 30
```

Testing
-------

[](#testing)

Run the test suite:

```
# Unit tests
./vendor/bin/phpunit packages/order-cart-bundle/tests/Unit

# Integration tests
./vendor/bin/phpunit packages/order-cart-bundle/tests/Integration

# Static analysis
./vendor/bin/phpstan analyse packages/order-cart-bundle -l 8
```

License
-------

[](#license)

Proprietary

Support
-------

[](#support)

For issues and questions, please contact the development team.

###  Health Score

38

—

LowBetter than 84% of packages

Maintenance77

Regular maintenance activity

Popularity8

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~9 days

Total

2

Last Release

177d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e354fdb316da535dfa8ba2e9193a473c403b6bc6fb9170778d1dc50e304c6e9d?d=identicon)[tourze](/maintainers/tourze)

---

Top Contributors

[![tourze](https://avatars.githubusercontent.com/u/13899502?v=4)](https://github.com/tourze "tourze (1 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tourze-order-cart-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/tourze-order-cart-bundle/health.svg)](https://phpackages.com/packages/tourze-order-cart-bundle)
```

###  Alternatives

[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.4k5.6M647](/packages/sylius-sylius)[contao/core-bundle

Contao Open Source CMS

1231.6M2.3k](/packages/contao-core-bundle)[sulu/sulu

Core framework that implements the functionality of the Sulu content management system

1.3k1.3M152](/packages/sulu-sulu)[prestashop/prestashop

PrestaShop is an Open Source e-commerce platform, committed to providing the best shopping cart experience for both merchants and customers.

9.0k15.4k](/packages/prestashop-prestashop)[ec-cube/ec-cube

EC-CUBE EC open platform.

78527.0k1](/packages/ec-cube-ec-cube)[shopware/platform

The Shopware e-commerce core

3.3k1.5M3](/packages/shopware-platform)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
