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 Bundle Laravel Package

dontdrinkandroot/api-platform-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require dontdrinkandroot/api-platform-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        DontDrinkAndRoot\ApiPlatformBundle\DontDrinkAndRootApiPlatformBundle::class => ['all' => true],
    ];
    
  2. First Use Case The bundle extends API Platform’s core functionality. Start by checking its EventSubscriber and StateProcessor implementations in src/EventSubscriber/ and src/StateProcessor/. For example:

    • Use the ApiPlatformRequestSubscriber to modify incoming requests (e.g., add headers, validate auth).
    • Apply the CustomStateProcessor to alter resource serialization/deserialization (e.g., sanitize output, inject computed fields).
  3. Where to Look First

    • src/Resources/config/services.yaml: Bundle’s default services and tags.
    • src/EventSubscriber/: Hooks for request/response lifecycle (e.g., ApiPlatformRequestSubscriber).
    • src/StateProcessor/: Custom state processors for entities (e.g., CustomStateProcessor).

Implementation Patterns

Common Workflows

  1. Extending API Platform Events Subscribe to API Platform’s events (e.g., kernel.request, api_platform.item.view) via the bundle’s subscribers:

    // config/services.yaml
    tags:
        - { name: 'kernel.event_subscriber', subscriber: 'App\EventSubscriber\MySubscriber' }
    

    Example: Modify the ApiPlatformRequestSubscriber to add CORS headers dynamically:

    public function onKernelRequest(GetResponseForControllerEvent $event) {
        $request = $event->getRequest();
        $request->headers->set('Access-Control-Allow-Origin', '*');
    }
    
  2. Custom State Processors Use the bundle’s CustomStateProcessor to transform entity data before serialization:

    // src/StateProcessor/CustomStateProcessor.php
    public function process($data, Operation $operation, array $uriVariables = [], array $context = [])
    {
        if ($data instanceof MyEntity) {
            $data->setComputedField('value'); // Add dynamic fields
        }
        return $data;
    }
    

    Register it in config/packages/api_platform.yaml:

    api_platform:
        formats:
            jsonld:
                mime_types: ['application/ld+json']
                context: '@api_platform.jsonld.context'
        state_processors:
            App\Entity\MyEntity: App\StateProcessor\CustomStateProcessor
    
  3. Integration with API Platform Resources Extend existing API Platform resources by leveraging the bundle’s traits or mixins:

    // src/Entity/MyEntity.php
    use DontDrinkAndRoot\ApiPlatformBundle\Traits\ApiPlatformTrait;
    
    class MyEntity {
        use ApiPlatformTrait;
        // ...
    }
    
  4. Validation and Filtering Use the bundle’s ApiPlatformFilter to add custom query parameters:

    # config/packages/api_platform.yaml
    api_platform:
        formats:
            jsonapi:
                mime_types: ['application/vnd.api+json']
        filters:
            - DontDrinkAndRoot\ApiPlatformBundle\Filter\CustomFilter
    

Best Practices

  • Tag Services Properly: Use api_platform.state_processor or kernel.event_subscriber tags for discoverability.
  • Leverage API Platform’s Ecosystem: Combine with api-platform/core and nelmio/cors-bundle for seamless integration.
  • Test Event Subscribers: Mock GetResponseForControllerEvent or ItemViewEvent in PHPUnit to verify behavior.

Gotchas and Tips

Pitfalls

  1. Service Overrides The bundle may override default API Platform services (e.g., api_platform.state_processor). If conflicts arise:

    • Check config/bundles.php for duplicate entries.
    • Use autoconfigure: false in services.yaml for custom implementations:
      services:
          App\StateProcessor\CustomStateProcessor:
              tags: ['api_platform.state_processor']
              autoconfigure: false
      
  2. Event Priority Subscribers may fire in unexpected orders. Use priority in tags to control execution:

    tags:
        - { name: 'kernel.event_subscriber', subscriber: 'App\EventSubscriber\MySubscriber', priority: 255 }
    
  3. Deprecated API Platform Features The bundle assumes API Platform ^3.0. If using ^2.7, some state processors may fail. Pin versions in composer.json:

    "api-platform/core": "^3.0",
    "dontdrinkandroot/api-platform-bundle": "^1.0"
    
  4. Circular Dependencies Avoid circular references between state processors and event subscribers. Use dependency injection sparingly:

    // Bad: Circular reference
    public function __construct(private CustomStateProcessor $processor) {}
    
    // Good: Pass data explicitly
    public function process($data, Operation $operation) {}
    

Debugging Tips

  1. Log Events Enable Symfony’s event dispatcher logging:

    # config/packages/monolog.yaml
    handlers:
        main:
            type: stream
            path: "%kernel.logs_dir%/%kernel.environment%.log"
            level: debug
            channels: ["event"]
    
  2. Check State Processor Context Dump the $context array in process() to debug serialization issues:

    public function process($data, Operation $operation, array $uriVariables, array $context) {
        error_log(print_r($context, true)); // Inspect context
        return $data;
    }
    
  3. Validate YAML Config Use Symfony’s config validator to catch syntax errors:

    php bin/console config:validate
    

Extension Points

  1. Custom Filters Extend DontDrinkAndRoot\ApiPlatformBundle\Filter\AbstractFilter to create reusable filters:

    class MyCustomFilter extends AbstractFilter {
        public function applyToCollection(CriteriaContext $context, Criteria $criteria) {
            // Add custom logic
        }
    }
    
  2. Dynamic Headers Modify ApiPlatformRequestSubscriber to inject headers conditionally:

    public function onKernelRequest(GetResponseForControllerEvent $event) {
        $request = $event->getRequest();
        if ($request->headers->has('X-Custom-Header')) {
            $request->headers->set('X-Processed', 'true');
        }
    }
    
  3. Serialization Groups Use the bundle’s traits to add serialization groups dynamically:

    use DontDrinkAndRoot\ApiPlatformBundle\Traits\SerializationGroupsTrait;
    
    class MyEntity {
        use SerializationGroupsTrait;
    
        public function getSerializationGroups(): array {
            return ['default', '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.
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle
dmstr/api-platform-utils-bundle
dmstr/api-configuration-bundle
chrisdev/ux-components
baks-dev/finances
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