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

Api Base Bundle Laravel Package

dbp/api-base-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require dbp/api-base-bundle
    

    Enable the bundle in config/bundles.php (Symfony):

    return [
        // ...
        Dbp\Relay\ApiBaseBundle\DbpApiBaseBundle::class => ['all' => true],
    ];
    
  2. Configuration Publish the default config:

    php bin/console dbp:api-base:install
    

    Review and customize config/packages/dbp_api_base.yaml (Symfony) or config/api-base.php (Laravel).

  3. First Use Case Generate a basic API endpoint:

    php artisan make:api-controller UserController --resource
    

    Extend the base controller (Dbp\Relay\ApiBaseBundle\Controller\ApiController) to leverage built-in features like:

    • Automatic DTO mapping
    • Validation
    • Pagination
    • Error handling

Implementation Patterns

Core Workflows

  1. DTO-Driven Development Use the @ApiResource annotation (Symfony) or ApiResource trait (Laravel) to define API endpoints:

    use Dbp\Relay\ApiBaseBundle\Annotation\ApiResource;
    
    #[ApiResource(
        collectionOperations: ['get', 'post'],
        itemOperations: ['get', 'put', 'delete']
    )]
    class UserController extends ApiController
    {
        // ...
    }
    
    • Laravel: Replace with #[ApiResource] trait or ApiResource facade.
  2. Validation & Serialization Leverage built-in validation via YAML/JSON schemas (e.g., config/api-base/validation/user.yaml):

    User:
      properties:
        name:
          type: string
          minLength: 2
    
    • Auto-validate incoming requests and return structured errors.
  3. Pagination & Filtering Use query parameters for pagination (?page=1&limit=10) and filtering (?name=John). Override configurePagination() in controllers for custom logic.

  4. Event-Driven Extensions Subscribe to events like ApiRequestEvent or ApiResponseEvent:

    // Symfony
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class MySubscriber implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return [
                'api.request' => 'onApiRequest',
            ];
        }
    }
    

Integration Tips

  • Laravel-Specific:

    • Use ApiBaseServiceProvider to bind interfaces to implementations.
    • Extend ApiBaseService for custom logic (e.g., app/Extensions/CustomApiService.php).
    • Override ApiBaseMiddleware for global request/response modifications.
  • Symfony-Specific:

    • Use api_base.twig templates for custom responses.
    • Integrate with Symfony’s Serializer for complex data transformations.
  • Shared:

    • Testing: Use ApiTestCase (Symfony) or ApiTestTrait (Laravel) for automated tests.
    • Documentation: Generate OpenAPI/Swagger docs via #[ApiResource] annotations.

Gotchas and Tips

Pitfalls

  1. Configuration Overrides

    • Issue: Custom config keys may conflict with defaults.
    • Fix: Use config/api-base.php (Laravel) or config/packages/dbp_api_base.yaml (Symfony) to explicitly override values. Example:
      'validation' => [
          'strict' => false, // Disable strict validation
      ],
      
  2. DTO Mapping Quirks

    • Issue: Nested DTOs may not map correctly if property names differ.
    • Fix: Use @SerializedName (Symfony) or $fillable (Laravel) to define mappings:
      #[SerializedName('user_name')]
      private string $name;
      
  3. Caching Headers

    • Issue: Over-aggressive caching may break API expectations.
    • Fix: Disable caching for mutable endpoints:
      public function configureResponseHeaders(): array
      {
          return [
              'Cache-Control' => 'no-cache, no-store, must-revalidate',
          ];
      }
      
  4. Event Dispatching

    • Issue: Events may fire in unexpected order.
    • Fix: Use priorities in event subscribers:
      'api.request' => ['onApiRequest', 255] // Highest priority
      

Debugging Tips

  • Enable Verbose Logging:

    php artisan api-base:debug --verbose
    

    (Laravel) or adjust Symfony’s monolog config.

  • Validate Annotations: Use php artisan api-base:validate (Laravel) or Symfony’s debug:container to check for misconfigured annotations.

  • API Response Inspection: Enable JSON pretty-printing in config:

    api_base:
        response:
            json_pretty_print: true
    

Extension Points

  1. Custom Validators Create a validator class and bind it in config:

    api_base:
        validation:
            custom_validators:
                - App\Validator\CustomUserValidator
    
  2. Middleware Stack Add custom middleware to the API stack (Laravel):

    $middleware->apiBaseMiddleware(function ($middleware) {
        $middleware->append(\App\Http\Middleware\CustomApiMiddleware::class);
    });
    
  3. Response Transformers Override transformResponse() in controllers or create a global transformer:

    use Dbp\Relay\ApiBaseBundle\Transformer\TransformerInterface;
    
    class CustomTransformer implements TransformerInterface
    {
        public function transform($data, string $format, array $context = [])
        {
            // Custom logic
        }
    }
    

    Register it in config:

    api_base:
        transformer:
            default: App\Transformer\CustomTransformer
    
  4. Error Handling Extend ApiException or create custom exception handlers:

    use Dbp\Relay\ApiBaseBundle\Exception\ApiException;
    
    throw new ApiException('Custom error', 403, [], 'custom.error.code');
    

    Map errors in config/api-base/errors.yaml.

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.
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator
equipc/laravel-email-database-log
adedsec/nova-translated-labels
wazza/laravel-db-encryption
hokny/laravel-generator
vonsogt/backup
jengo/queues
jeremykenedy/laravel-observability
coleus/frame
thtg88/journalism
filagora/filagora-ai-forums