Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Sulu Shopping Cart Laravel Package

comsa/sulu-shopping-cart

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation Add the package via Composer:

    composer require comsa/sulu-shopping-cart
    

    Ensure SuluShoppingCartBundle is enabled in config/bundles.php:

    Comsa\SuluShoppingCartBundle\SuluShoppingCartBundle::class => ['all' => true],
    
  2. Basic Setup Run migrations to create the required database tables:

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  3. First Use Case: Adding a Product to Cart Inject the CartManager service and use it to add a product:

    use Comsa\SuluShoppingCartBundle\Manager\CartManagerInterface;
    
    class MyController
    {
        public function __construct(private CartManagerInterface $cartManager) {}
    
        public function addToCart(Product $product)
        {
            $cart = $this->cartManager->getCart();
            $cart->addProduct($product);
            $this->cartManager->persistCart($cart);
        }
    }
    
  4. Where to Look First

    • Documentation: Check the GitLab repository for setup guides and API docs.
    • Configuration: Review config/packages/sulu_shopping_cart.yaml for default settings.
    • Services: Explore CartManagerInterface and related services in src/Manager/.

Implementation Patterns

Core Workflows

  1. Cart Management

    • Retrieve/Update Cart:
      $cart = $this->cartManager->getCart(); // Gets or creates a cart for the current user.
      $cart->updateProductQuantity($productId, 3);
      $this->cartManager->persistCart($cart);
      
    • Clear Cart:
      $this->cartManager->clearCart();
      
  2. Product Integration

    • Define Product Rules: Use ProductRuleInterface to validate products (e.g., stock, pricing):
      $rule = new StockRule(5); // Allow max 5 items.
      $this->cartManager->addProductRule($rule);
      
    • Custom Product Models: Extend ProductInterface to integrate with your product system:
      class MyProduct implements ProductInterface
      {
          public function getId(): string { /* ... */ }
          public function getPrice(): float { /* ... */ }
          // ...
      }
      
  3. Checkout Process

    • Validate Cart:
      if (!$this->cartManager->validateCart($cart)) {
          throw new \RuntimeException("Cart validation failed.");
      }
      
    • Process Payment: Integrate with a payment gateway (e.g., Stripe) after cart validation.
  4. Persistence

    • Session vs. Database: Configure storage in sulu_shopping_cart.yaml:
      sulu_shopping_cart:
          storage: database # or 'session'
      

Integration Tips

  • Symfony Events: Listen to cart.product.added or cart.updated events for real-time updates:
    $dispatcher->addListener('cart.product.added', function (CartEvent $event) {
        // Send notification, update UI, etc.
    });
    
  • APIs: Use CartRepositoryInterface to fetch carts by ID (e.g., for order history):
    $cart = $this->cartRepository->findById($cartId);
    
  • Testing: Mock CartManagerInterface in unit tests to isolate logic:
    $this->cartManager = $this->createMock(CartManagerInterface::class);
    $this->cartManager->method('getCart')->willReturn($mockCart);
    

Gotchas and Tips

Common Pitfalls

  1. Session Storage Limitations

    • Issue: Session storage may not persist across devices or after browser closure.
    • Fix: Use database storage for critical applications or implement a hybrid approach.
  2. Product Rule Conflicts

    • Issue: Overlapping rules (e.g., StockRule + MaxQuantityRule) may cause unexpected rejections.
    • Fix: Prioritize rules by order or use a RuleValidator to handle conflicts:
      $validator = new RuleValidator([$rule1, $rule2]);
      if (!$validator->isValid($product)) { /* ... */ }
      
  3. Cart Expiration

    • Issue: Carts may expire if not persisted (e.g., session timeout).
    • Fix: Configure ttl (time-to-live) in sulu_shopping_cart.yaml:
      sulu_shopping_cart:
          ttl: 3600 # 1 hour in seconds
      
  4. Database Locking

    • Issue: Concurrent cart updates may cause deadlocks.
    • Fix: Use transactions or optimistic locking:
      $cart = $this->cartRepository->find($id);
      $cart->lock(); // If supported.
      $cart->addProduct($product);
      $this->cartRepository->save($cart);
      

Debugging Tips

  • Enable Logging: Add debug logs for cart operations:
    sulu_shopping_cart:
        debug: true
    
  • Check Events: Use Symfony’s profiler to inspect dispatched events (e.g., cart.updated).
  • Validate Entities: Ensure Product and CartItem entities implement all required interfaces/methods.

Extension Points

  1. Custom Storage

    • Implement StorageInterface to use Redis, Elasticsearch, etc.:
      class RedisStorage implements StorageInterface
      {
          public function save(Cart $cart) { /* ... */ }
          public function findById(string $id) { /* ... */ }
      }
      
    • Register the service in services.yaml:
      Comsa\SuluShoppingCartBundle\Storage\StorageInterface: '@redis_storage'
      
  2. Custom Rules

    • Create a ProductRule for business logic (e.g., "Blacklist categories"):
      class CategoryBlacklistRule implements ProductRuleInterface
      {
          public function isAllowed(ProductInterface $product): bool
          {
              return !in_array($product->getCategory(), ['electronics', 'restricted']);
          }
      }
      
  3. API Extensions

    • Add custom endpoints for cart operations using Symfony’s JsonResponse:
      #[Route('/api/cart', methods: ['POST'])]
      public function updateCart(Request $request): JsonResponse
      {
          $data = json_decode($request->getContent(), true);
          $cart = $this->cartManager->getCart();
          $cart->setItems($data['items']);
          $this->cartManager->persistCart($cart);
          return new JsonResponse(['success' => true]);
      }
      
  4. Frontend Integration

    • Use the CartSerializer to convert carts to JSON for JavaScript frameworks:
      $serializer = new CartSerializer();
      $json = $serializer->serialize($cart);
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
coleus/frame
thtg88/journalism
filagora/filagora-ai-forums
rlacerda83/query-parser
socialdept/atp-orm
cboxdk/laravel-assistant-client
socialdept/atp-resolver
socialdept/tenant-domains
tautvydasr/blade-class-names
socialdept/color-scales
maherelgamil/controller
coleus/widgets
coleus/table
coleus/users
coleus/music
coleus/health
coleus/calendar
coleus/notes
coleus/support
coleus/settings