Weave Code
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

Symfony Bundle Laravel Package

commercetools/symfony-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require commercetools/symfony-bundle
    

    Ensure composer config extra.symfony.allow-contrib true is set (Symfony Flex requirement).

  2. Configuration Add the bundle to config/bundles.php:

    return [
        // ...
        Commercetools\ClientBundle\CommercetoolsClientBundle::class => ['all' => true],
        Commercetools\SdkBundle\CommercetoolsSdkBundle::class => ['all' => true],
    ];
    
  3. Environment Setup Define credentials in .env:

    COMMERCETOOLS_CLIENT_ID=your_client_id
    COMMERCETOOLS_CLIENT_SECRET=your_client_secret
    COMMERCETOOLS_PROJECT_KEY=your_project_key
    COMMERCETOOLS_API_URL=https://api.europe-west1.gcp.commercetools.com
    COMMERCETOOLS_TOKEN_URL=https://auth.europe-west1.gcp.commercetools.com
    
  4. First Use Case Inject the client into a service/controller:

    use Commercetools\Client\ClientBuilder;
    use Commercetools\Client\Http\Middleware\AuthMiddleware;
    
    public function __construct(private ClientBuilder $clientBuilder) {}
    
    public function fetchProducts(): array {
        $client = $this->clientBuilder->buildClient();
        $products = $client->search()->products()->post(['query' => '*' ]);
        return $products->getBody()['results'];
    }
    

Implementation Patterns

Core Workflows

  1. Service Integration Use dependency injection for the ClientBuilder and HttpClient:

    // services.yaml
    services:
        App\Service\ProductService:
            arguments:
                $clientBuilder: '@commercetools.client_builder'
    
  2. API Calls Wrap SDK calls in domain services to abstract complexity:

    class ProductService {
        public function getProductById(string $id): ?Product {
            return $this->clientBuilder->buildClient()
                ->withRequestExecutor(new RequestExecutor())
                ->getById(Product::class, $id);
        }
    }
    
  3. Twig Integration Pass SDK models directly to Twig templates:

    {% for product in products %}
        <h2>{{ product.name.en }}</h2>
        <p>{{ product.price.value | currency }}</p>
    {% endfor %}
    
  4. Console Commands Leverage built-in commands for bulk operations:

    php bin/console commercetools:products:import ./data/products.json
    

Best Practices

  • Caching: Cache API responses using Symfony’s cache system:
    $cache = $this->container->get('commercetools.cache');
    $cachedProducts = $cache->get('products', function() use ($client) {
        return $client->search()->products()->post(['query' => '*']);
    });
    
  • Error Handling: Use middleware to handle API errors globally:
    $client = $this->clientBuilder->buildClient()
        ->withMiddleware(new ErrorHandlingMiddleware());
    

Gotchas and Tips

Common Pitfalls

  1. Authentication Issues

    • Ensure .env variables are correctly set and the token URL matches your region.
    • Debug token generation with:
      php bin/console debug:container commercetools.auth_middleware
      
  2. SDK Version Mismatch

    • The bundle pins the PHP SDK version. Update both packages simultaneously:
      composer require commercetools/sdk:^x.y.z commercetools/symfony-bundle:^x.y.z
      
  3. Rate Limiting

    • Commercetools enforces rate limits. Implement exponential backoff in middleware:
      $client->withMiddleware(new RateLimitMiddleware());
      
  4. Twig Template Errors

    • SDK models may not be serializable by default. Use @commercetools.twig.model_serializer:
      {{ dump(product | commercetools_model_serializer) }}
      

Debugging Tips

  • Log API Requests Enable debug mode in config/packages/commercetools.yaml:

    commercetools:
        debug: true
    

    Logs will appear in var/log/dev.log.

  • Validate Payloads Use the Validator service to validate SDK models before submission:

    $validator = $this->container->get('validator');
    $errors = $validator->validate($product);
    

Extension Points

  1. Custom Middleware Extend the client with custom middleware (e.g., logging, retries):

    $client->withMiddleware(new CustomLoggingMiddleware());
    
  2. Event Subscribers Subscribe to SDK events (e.g., ProductCreatedEvent) for real-time updates:

    use Commercetools\Sdk\Event\EventSubscriberInterface;
    
    class ProductEventSubscriber implements EventSubscriberInterface {
        public static function getSubscribedEvents(): array {
            return [
                'product.created' => 'onProductCreated',
            ];
        }
    }
    
  3. Custom Console Commands Extend the base command classes for project-specific logic:

    use Commercetools\SdkBundle\Command\AbstractCommand;
    
    class CustomProductCommand extends AbstractCommand {
        protected function configure(): void {
            $this->setName('commercetools:products:custom');
        }
    }
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware