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

coka/api-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

Since this is a Symfony bundle, integration with Laravel requires Bridge or Symfony wrapper (e.g., symfony/http-foundation + symfony/routing). For Laravel 8/9, use:

composer require symfony/http-foundation symfony/routing
  1. Register the Bundle (if using Symfony components directly):

    • Manually instantiate the bundle in config/app.php (not natively supported in Laravel).
    • Alternatively, wrap its logic in a Laravel service provider.
  2. First Use Case: API Resource Controller The bundle likely provides traits for RESTful controllers. Example:

    use Coka\ApiBundle\Controller\AbstractApiController;
    
    class UserController extends AbstractApiController
    {
        public function getList(): Response
        {
            return $this->handleList(User::class, [
                'fields' => ['id', 'name', 'email']
            ]);
        }
    }
    
    • Route it:
      Route::get('/users', [UserController::class, 'getList']);
      
  3. Key Files to Review:

    • src/Resources/doc/index.md (documentation)
    • src/Controller/AbstractApiController.php (base controller logic)
    • src/EventListener/ (for hooks like validation/error handling).

Implementation Patterns

1. Controller Patterns

  • AbstractApiController: Extend this for CRUD operations. Key methods:
    • handleList(): Fetch paginated collections with filtering.
    • handleGet(): Single resource retrieval.
    • handleCreate()/handleUpdate(): Form request handling.
  • Example Workflow:
    // GET /users?filter[name]=John
    public function getList(): Response
    {
        return $this->handleList(User::class, [
            'filter' => ['name' => request('name')],
            'paginate' => 15,
            'sort' => ['name' => 'asc']
        ]);
    }
    

2. Request/Response Handling

  • Input Validation: Use Symfony’s Validator via the bundle’s traits.
    use Coka\ApiBundle\Validator\Constraints as ApiAssert;
    
    /**
     * @ApiAssert\Valid()
     */
    public function handleCreate(Request $request): Response
    {
        // ...
    }
    
  • API Responses: Standardized JSON responses with HTTP codes.
    return $this->createResponse([
        'data' => $user,
        'meta' => ['status' => 'created']
    ], 201);
    

3. Event-Driven Extensions

  • Listen to bundle events (e.g., api.pre_handle) to modify requests/responses:
    // In a service provider
    $dispatcher->addListener(
        'api.pre_handle',
        function (ApiEvent $event) {
            $event->setData(['custom_field' => true]);
        }
    );
    

4. Integration with Laravel Services

  • Eloquent Models: Pass Eloquent queries to bundle methods:
    $this->handleList(User::query()->where('active', true));
    
  • API Resources: Combine with Laravel’s ApiResource for serialization:
    class UserResource extends ApiResource
    {
        public function toArray($request)
        {
            return [
                'id' => $this->id,
                'name' => $this->name,
            ];
        }
    }
    

Gotchas and Tips

1. Symfony-Laravel Mismatches

  • Routing: The bundle uses Symfony’s Router. For Laravel, mock routes or use symfony/routing:
    $router = new Router();
    $router->addCollection($this->container->get('router')->getRouteCollection());
    
  • Dependency Injection: Avoid container()->get(); use Laravel’s DI container or bind services manually.

2. Debugging

  • Event Debugging: Enable Symfony’s event dispatcher logging:
    $dispatcher->addListener('api.*', function ($event) {
        \Log::debug('API Event:', [$event->getName(), $event->getData()]);
    });
    
  • Response Inspection: Override createResponse() to log payloads:
    protected function createResponse($data, int $status = 200): Response
    {
        \Log::info('API Response', [$data, $status]);
        return response()->json($data, $status);
    }
    

3. Configuration Quirks

  • No Laravel Config: The bundle expects Symfony’s config/packages/oka_api.yaml. Replicate in config/oka_api.php:
    return [
        'default_limit' => 20,
        'allowed_methods' => ['GET', 'POST', 'PUT', 'DELETE'],
    ];
    
  • Override Defaults: Use Laravel’s mergeConfigFrom in a service provider.

4. Extension Points

  • Custom Validators: Extend Coka\ApiBundle\Validator\Constraints\Valid:
    namespace App\Validator;
    
    use Symfony\Component\Validator\Constraint;
    
    class CustomValid extends Constraint
    {
        // ...
    }
    
  • Middleware: Wrap bundle controllers with Laravel middleware:
    Route::middleware(['auth:sanctum'])->group(function () {
        Route::get('/users', [UserController::class, 'getList']);
    });
    

5. Performance Tips

  • Caching: Cache frequent handleList() calls with Laravel’s cache:
    $cacheKey = "api_users_{$request->queryString}";
    return Cache::remember($cacheKey, now()->addMinutes(5), function () {
        return $this->handleList(User::class);
    });
    
  • Query Optimization: Use Eloquent’s cursor() for large datasets in handleList().

6. Deprecation Notes

  • Last Release (2019): Test thoroughly; some Symfony 4.x features may break in newer versions.
  • Alternatives: Consider modern Laravel packages like:
    • laravel/api-resources (for API resources).
    • spatie/laravel-query-builder (for filtering/sorting).
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.
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor
spatie/laravel-javascript-views