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

Api Platform Events Bundle Laravel Package

alanpoulain/api-platform-events-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require alanpoulain/api-platform-events-bundle
    

    Ensure ApiPlatformEventsBundle is enabled in config/bundles.php:

    return [
        // ...
        ApiPlatform\EventsBundle\ApiPlatformEventsBundle::class => ['all' => true],
    ];
    
  2. First Use Case: Logging Operations Create a listener to log GraphQL operations (e.g., src/EventListener/ApiPlatformLogger.php):

    namespace App\EventListener;
    
    use ApiPlatform\Events\PreReadEvent;
    use Psr\Log\LoggerInterface;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class ApiPlatformLogger implements EventSubscriberInterface
    {
        public function __construct(private LoggerInterface $logger) {}
    
        public static function getSubscribedEvents(): array
        {
            return [
                PreReadEvent::class => 'logPreRead',
                PostWriteEvent::class => 'logPostWrite',
            ];
        }
    
        public function logPreRead(PreReadEvent $event): void
        {
            $this->logger->info('Pre-read operation', [
                'resource' => $event->getResource(),
                'operation' => $event->getOperationName(),
                'context' => $event->getContext(),
            ]);
        }
    
        // Add logPostWrite method similarly
    }
    
  3. Verify Events Trigger a GraphQL query/mutation (e.g., via API Platform’s GraphQL Playground) and check logs or debug output.


Implementation Patterns

Common Workflows

  1. Conditional Logic in Events Use events to modify behavior dynamically (e.g., PreWriteEvent for pre-saving data transformations):

    public function onPreWrite(PreWriteEvent $event): void
    {
        $data = $event->getData();
        if ($data['status'] === 'draft') {
            $data['published_at'] = null;
            $event->setData($data); // Modify input
        }
    }
    
  2. Cross-Cutting Concerns

    • Authorization: Validate operations in PreReadEvent/PreWriteEvent.
    • Audit Trails: Log changes in PostWriteEvent.
    • Caching: Invalidate caches in PostWriteEvent.
  3. Context Utilization Access the context array for metadata (e.g., user roles, request headers):

    $user = $event->getContext()['user'] ?? null;
    if (!$user->hasRole('ROLE_ADMIN')) {
        throw new \RuntimeException('Unauthorized');
    }
    
  4. Event Chaining Dispatch custom events within listeners to decouple logic:

    $this->eventDispatcher->dispatch(new CustomEvent($event->getData()));
    

Integration Tips

  • Symfony Messenger: Forward events to async workers for heavy tasks.
  • Doctrine Lifecycle Callbacks: Combine with @PrePersist/@PostUpdate for hybrid logic.
  • GraphQL Resolvers: Use events to avoid duplicating resolver logic (e.g., shared validation).

Gotchas and Tips

Pitfalls

  1. REST Limitation The bundle only supports GraphQL (per README). For REST, use API Platform’s native stages or wait for the Stages RFC.

  2. Event Timing

    • PreDeserializeEvent/PostDeserializeEvent only fire for mutations, not queries.
    • PreReadEvent fires before data fetching (use for early validation).
  3. Data Mutability

    • Immutable Data: Some events (e.g., PostReadEvent) provide read-only data. Clone if modification is needed:
      $data = clone $event->getData();
      
  4. Context Overrides Avoid modifying the context array directly—use setContext() if needed:

    $event->setContext(array_merge($event->getContext(), ['custom_key' => 'value']));
    

Debugging

  • Event Dumping: Use Symfony’s debug:event-dispatcher to list dispatched events:
    php bin/console debug:event-dispatcher
    
  • Priority Conflicts: Ensure listeners have correct priority (default: 0). Higher values run later:
    public static function getSubscribedEvents(): array
    {
        return [
            PreWriteEvent::class => ['onPreWrite', 255], // High priority
        ];
    }
    

Extension Points

  1. Custom Events Extend the bundle by creating your own events (e.g., PostProcessEvent) and dispatch them in listeners.

  2. Event Subscriber Interfaces Implement EventSubscriberInterface for type-safe event handling (IDE autocompletion).

  3. Configuration Override default event classes by binding your own services (e.g., for testing):

    # config/services.yaml
    ApiPlatform\Events\PreReadEvent: '@app.custom_pre_read_event'
    
  4. Performance For high-traffic APIs, benchmark event listeners—some operations (e.g., DB queries in PreReadEvent) may impact performance. Use profiling tools like Blackfire.

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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui