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

Plug Symfony Laravel Package

croct/plug-symfony

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require croct/plug-symfony
    

    Add the bundle to config/bundles.php:

    return [
        // ...
        Croct\Plug\Symfony\CroctPlugBundle::class => ['all' => true],
    ];
    
  2. Configuration Publish the default config:

    php bin/console croct:plug:install
    

    Update config/packages/croct_plug.yaml with your API key and environment (e.g., sandbox or production).

  3. First Use Case Inject the CroctPlugClient into a controller/service and fetch dynamic content:

    use Croct\Plug\Symfony\Client\CroctPlugClient;
    
    class MyController extends AbstractController
    {
        public function __construct(private CroctPlugClient $client) {}
    
        public function showContent(): Response
        {
            $response = $this->client->getContent('your-content-id');
            return $this->render('template.html.twig', [
                'content' => $response->getContent(),
            ]);
        }
    }
    
  4. Twig Integration Enable Twig extensions in config/packages/twig.yaml:

    twig:
        globals:
            croct: '@croct.plug.twig_extension'
    

    Use in templates:

    {{ croct.render('your-content-id') }}
    

Implementation Patterns

Core Workflows

  1. Content Fetching

    • Synchronous: Use CroctPlugClient for real-time requests (e.g., in controllers).
      $this->client->getContent('id', ['userId' => 123]);
      
    • Asynchronous: Cache responses with Symfony’s cache system:
      $cache = $this->client->getCache();
      $content = $cache->get('content:id', fn() => $this->client->getContent('id'));
      
  2. Personalization Pass user context via getContent() options:

    $this->client->getContent('id', [
        'userId' => $user->id,
        'traits' => ['premium' => true],
    ]);
    
  3. Event-Driven Updates Subscribe to Croct’s webhooks (via CroctPlugWebhookEventSubscriber) to handle real-time content updates:

    # config/packages/croct_plug.yaml
    croct_plug:
        webhooks:
            enabled: true
            secret: 'your-webhook-secret'
    
  4. Dependency Injection Prefer constructor injection for CroctPlugClient and CroctPlugCache:

    public function __construct(
        private CroctPlugClient $client,
        private CroctPlugCache $cache
    ) {}
    

Integration Tips

  1. Environment-Specific Config Use Symfony’s parameter bags for environment variables:

    # config/packages/croct_plug.yaml
    croct_plug:
        api_key: '%env(CROCT_API_KEY)%'
        environment: '%kernel.environment%'
    
  2. Error Handling Wrap Croct calls in try-catch blocks to handle CroctPlugException:

    try {
        $response = $this->client->getContent('id');
    } catch (CroctPlugException $e) {
        $this->addFlash('error', $e->getMessage());
        return $this->redirectToRoute('home');
    }
    
  3. Testing Mock CroctPlugClient in PHPUnit:

    $mock = $this->createMock(CroctPlugClient::class);
    $mock->method('getContent')->willReturn(new CroctPlugResponse(['html' => '<p>Mocked</p>']));
    $this->controller->setClient($mock);
    
  4. Performance

    • Cache Layer: Use CroctPlugCache with a short TTL (e.g., 5 minutes) for frequently accessed content.
    • Batch Fetching: Fetch multiple content IDs in a single request:
      $this->client->getContents(['id1', 'id2']);
      

Gotchas and Tips

Pitfalls

  1. API Key Exposure

    • Risk: Hardcoding API keys in config files.
    • Fix: Use Symfony’s %env() or .env files:
      croct_plug:
          api_key: '%env(CROCT_API_KEY)%'
      
  2. Rate Limiting

    • Croct enforces rate limits (e.g., 60 requests/minute). Cache aggressively to avoid hitting limits.
    • Debugging: Check CroctPlugException for 429 Too Many Requests errors.
  3. Twig Auto-escaping

    • Croct’s HTML responses are not auto-escaped in Twig. Use |raw if needed:
      {{ croct.render('id')|raw }}
      
  4. Webhook Verification

    • Always verify webhook payloads using the CroctPlugWebhookValidator:
      $validator = new CroctPlugWebhookValidator('your-secret');
      if (!$validator->validate($request->getContent(), $request->headers)) {
          throw new \RuntimeException('Invalid webhook signature');
      }
      

Debugging

  1. Enable Logging Configure Monolog in config/packages/monolog.yaml:

    monolog:
        handlers:
            croct:
                type: stream
                path: "%kernel.logs_dir%/croct.log"
                level: debug
    

    Croct logs will include request/response details and errors.

  2. HTTP Debugging Use Symfony’s PROFILER to inspect Croct HTTP calls:

    _PROFILE=1 php bin/console server:run
    
  3. Common Errors

    Error Cause Solution
    Invalid API Key Wrong api_key in config. Verify .env or config file.
    Content Not Found Invalid contentId. Check Croct Dashboard for correct IDs.
    Network Timeout Croct API downtime. Retry with exponential backoff.
    Twig Error: Undefined method Twig extension not registered. Ensure croct_plug.twig_extension is in globals.

Extension Points

  1. Custom Cache Adapter Extend CroctPlugCache to use Redis or Doctrine Cache:

    use Croct\Plug\Symfony\Cache\CroctPlugCache;
    use Symfony\Contracts\Cache\CacheInterface;
    
    class RedisCroctPlugCache extends CroctPlugCache
    {
        public function __construct(CacheInterface $cache) {
            parent::__construct($cache);
        }
    }
    
  2. Content Preprocessing Hook into CroctPlugResponse to modify content before rendering:

    $response = $this->client->getContent('id');
    $response->setContent(
        str_replace('{{placeholder}}', 'Custom Value', $response->getContent())
    );
    
  3. Event Listeners Subscribe to CroctPlugEvents (e.g., CONTENT_FETCHED) for analytics:

    use Croct\Plug\Symfony\Event\CroctPlugEvents;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class CroctAnalyticsSubscriber implements EventSubscriberInterface
    {
        public static function getSubscribedEvents(): array
        {
            return [
                CroctPlugEvents::CONTENT_FETCHED => 'logContentFetch',
            ];
        }
    
        public function logContentFetch(CroctPlugEvent $event) {
            // Send analytics to your service.
        }
    }
    
  4. Custom Content Types Extend CroctPlugClient to support non-HTML responses (e.g., JSON):

    $client->getContent('id', [], CroctPlugClient::FORMAT_JSON);
    
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