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

Php Api Routing Bundle Laravel Package

kleijnweb/php-api-routing-bundle

Laravel-friendly bundle for building API routing with a structured approach. Helps organize route definitions, controllers, and versioned endpoints into a cleaner setup for small to medium PHP APIs.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the package via Composer in your Laravel project (though originally for Symfony, it can be adapted via Laravel’s Symfony bridge):

    composer require kleijnweb/php-api-routing-bundle
    

    Note: Since this is a Symfony bundle, you’ll need to manually bridge it with Laravel’s service container or use a Symfony-compatible facade.

  2. Basic Setup

    • Register the bundle in your Symfony-based Laravel app (if using Symfony components) or mock its routing logic via a custom Laravel service provider.
    • Define OpenAPI routes in a YAML/JSON file (e.g., config/openapi_routes.yaml):
      paths:
        /api/users:
          get:
            tags: [Users]
            summary: Get all users
            operationId: getUsers
      
  3. First Use Case

    • Generate a Symfony router instance and load the OpenAPI spec:
      use Symfony\Component\Routing\Loader\YamlFileLoader;
      use Symfony\Component\Routing\RouteCollection;
      
      $loader = new YamlFileLoader();
      $collection = $loader->load('config/openapi_routes.yaml');
      $router = new Symfony\Component\Routing\Router($collection);
      
    • Use the router in Laravel’s middleware or controller to validate requests against OpenAPI paths:
      $request = $this->getRequest();
      $context = new Symfony\Component\Routing\RequestContext();
      $matcher = new Symfony\Component\Routing\Matcher\UrlMatcher($collection, $context);
      try {
          $matcher->match($request->getPathInfo());
          // Proceed if route exists in OpenAPI spec
      } catch (\Exception $e) {
          abort(404, 'Route not documented in OpenAPI spec.');
      }
      

Implementation Patterns

Usage Patterns

  1. API Documentation-Driven Routing

    • Use the OpenAPI spec as a single source of truth for routes. Update the YAML/JSON file to reflect changes in your API, then regenerate routes dynamically.
    • Example workflow:
      // In a Laravel service provider's boot method
      $this->app->singleton('openapi.router', function () {
          $loader = new YamlFileLoader();
          $collection = $loader->load(storage_path('openapi_routes.yaml'));
          return new Symfony\Component\Routing\Router($collection);
      });
      
  2. Request Validation

    • Leverage the router to validate incoming requests against documented paths before processing:
      public function handle(Request $request, Closure $next) {
          $router = app('openapi.router');
          $context = new RequestContext();
          $matcher = new UrlMatcher($router->getRouteCollection(), $context);
          $matcher->match($request->path());
          return $next($request);
      }
      
      Register this middleware globally or per-route group (e.g., api).
  3. Dynamic Route Generation

    • Generate URL paths from OpenAPI specs for API clients:
      $generator = new Symfony\Component\Routing\Generator\UrlGenerator($router, $context);
      $url = $generator->generate('getUsers', [], UrlGeneratorInterface::ABSOLUTE_URL);
      

Workflows

  • CI/CD Integration

    • Add a script to validate OpenAPI routes against your Laravel routes in CI (e.g., using phpunit or a custom script).
    • Example:
      php artisan openapi:validate
      
      (Note: Requires custom artisan command to bridge Symfony router with Laravel routes.)
  • IDE Autocompletion

Integration Tips

  • Laravel-Symfony Bridge

    • Use symfony/http-foundation and symfony/routing packages to avoid direct bundle integration:
      composer require symfony/http-foundation symfony/routing
      
    • Wrap Symfony’s Router in a Laravel service provider for dependency injection.
  • OpenAPI Schema Validation

    • Combine with packages like zircote/swagger-php to validate request/response schemas:
      use Zircote\Swagger\Scanner;
      
      $openapi = Scanner::scan([base_path('routes')]);
      $validator = new \Zircote\Swagger\Validator();
      $validator->validate($openapi);
      

Gotchas and Tips

Pitfalls

  1. Archived Package

    • The package is archived and may lack updates. Expect no official support or compatibility fixes for newer Symfony/Laravel versions.
    • Workaround: Fork the repository and maintain it locally, or migrate to alternatives like:
  2. Symfony Dependency Overhead

    • The bundle pulls in Symfony components, which may conflict with Laravel’s DI container or routing system.
    • Tip: Use symfony/routing in isolation to avoid bloat:
      composer require symfony/routing --ignore-platform-reqs
      
  3. YAML/JSON Parsing Quirks

    • The bundle expects strict OpenAPI 2.0/3.0 YAML/JSON syntax. Invalid specs will throw cryptic errors.
    • Tip: Validate your spec using Swagger Validator before integrating.
  4. Middleware vs. Controller Validation

    • Validating routes in middleware (as shown above) is efficient but may obscure errors. For debugging, log matched routes:
      $match = $matcher->match($request->path());
      \Log::debug('Matched OpenAPI route:', ['route' => $match]);
      

Debugging

  • Route Matching Failures

    • If a request fails to match, dump the RouteCollection to verify routes:
      dd($router->getRouteCollection()->getResources());
      
    • Check for typos in operationId or path definitions in your YAML.
  • Circular Dependencies

    • If using Laravel’s route caching (php artisan route:cache), clear it after updating OpenAPI specs:
      php artisan route:clear
      

Extension Points

  1. Custom Route Loaders

    • Extend YamlFileLoader to support additional file formats (e.g., JSON) or remote specs:
      class JsonFileLoader extends FileLoader {
          public function load($resource, $type = null) { /* ... */ }
      }
      
  2. Laravel Route Integration

    • Sync OpenAPI routes with Laravel’s route definitions using a custom artisan command:
      // app/Console/Commands/SyncOpenApiRoutes.php
      public function handle() {
          $openapiRoutes = $this->loadOpenApiRoutes();
          foreach ($openapiRoutes as $path => $methods) {
              foreach ($methods as $method) {
                  Route::{$method}($path, fn() => 'OpenAPI Controller');
              }
          }
      }
      
  3. OpenAPI Server Validation

    • Use the bundle to validate incoming requests against the spec before Laravel’s routing:
      $request = $this->getRequest();
      $router = app('openapi.router');
      try {
          $router->getMatcher()->match($request->getPathInfo());
          // Proceed to Laravel routing
      } catch (\Exception $e) {
          abort(400, 'Request does not match OpenAPI spec.');
      }
      

Tips

  • Partial Adoption

  • Performance

    • Cache the RouteCollection in Laravel’s cache:
      $collection = Cache::remember('openapi.routes', now()->addHours(1), function() {
          return $loader->load('config/openapi_routes.yaml');
      });
      
  • Testing

    • Write PHPUnit tests to assert route coverage:
      public function testOpenApiRouteCoverage() {
          $router = app('openapi.router');
          $this->assertTrue($router->getRouteCollection()->has('getUsers'));
      }
      
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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