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

Dispatch Laravel Package

equip/dispatch

Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Middleware Dispatcher Pattern: The package aligns well with Laravel’s middleware stack, enabling dynamic, HTTP Interop-compatible middleware dispatching (e.g., PSR-15). This is particularly valuable for:
    • Modular middleware (e.g., A/B testing, feature flags, or third-party integrations).
    • Conditional routing (e.g., tenant-based middleware, rate limiting by route).
    • Decoupling middleware logic from route definitions (e.g., injecting middleware via config or database).
  • PSR-15 Compatibility: Laravel’s native middleware (Closure, Middleware, GroupMiddleware) can be bridged via HTTP Interop adapters (e.g., zend-stratigility or laminas/laminas-http-handler-runner), though this introduces abstraction overhead.
  • Use Cases:
    • Dynamic middleware injection (e.g., per-user, per-request, or environment-specific).
    • Legacy system integration where middleware must conform to PSR-15.
    • Plugin architectures where middleware is loaded at runtime.

Integration Feasibility

  • Laravel-Specific Challenges:
    • Laravel’s middleware stack is PSR-15-aware but not natively PSR-15-compliant. The package would require:
      • A PSR-15 middleware adapter (e.g., wrapping Laravel middleware in Psr\Http\Message\ResponseInterface/RequestInterface).
      • Middleware priority handling: Laravel’s $middlewarePriority may conflict with dynamic dispatch order.
    • Service Container Integration: The package’s dependency injection (if any) must align with Laravel’s IoC container (e.g., binding PSR-15 middleware as Laravel middleware).
  • Testing Complexity:
    • Middleware interactions (e.g., short-circuiting, exceptions) must be validated in both Laravel’s and PSR-15’s contexts.
    • Mocking Psr\Http\Message objects in Laravel tests may require additional tooling (e.g., php-http/mock-client).

Technical Risk

Risk Area Severity Mitigation Strategy
PSR-15/Laravel Bridge High Develop a lightweight adapter layer (e.g., LaravelMiddlewareToPsr15).
Middleware Ordering Medium Document priority rules and provide a MiddlewareDispatcher facade for explicit control.
Performance Overhead Low Benchmark PSR-15 dispatch vs. native Laravel middleware (expect minimal impact).
Dependency Bloat Low Use composer require only for PSR-15 adapters (e.g., laminas/laminas-diactoros).
License Compliance Low MIT license is compatible; no conflicts with Laravel’s MIT license.

Key Questions

  1. Why PSR-15?
    • Is the goal to integrate with non-Laravel PSR-15 middleware (e.g., Symfony, Laminas)?
    • Or is this for internal modularity (where Laravel’s native middleware suffices)?
  2. Middleware Lifecycle:
    • How will the dispatcher handle middleware that modifies Request/Response objects (e.g., adding headers, rewriting URLs)?
  3. Error Handling:
    • How are PSR-15 middleware exceptions (e.g., RequestHandlerInterface failures) translated to Laravel’s error responses?
  4. Performance:
    • What’s the expected overhead of PSR-15 dispatch vs. native Laravel middleware?
  5. Alternatives:
    • Could Laravel’s Middleware::when() or Middleware::prepend() achieve similar goals without PSR-15?
  6. Testing Strategy:
    • How will integration tests verify PSR-15 middleware behavior in a Laravel context?

Integration Approach

Stack Fit

  • Laravel Core Compatibility:
    • Middleware: The package can integrate with Laravel’s $middleware array, Kernel.php, or service provider bindings.
    • HTTP Layer: Requires PSR-7/PSR-15 adapters (e.g., nyholm/psr7, laminas/laminas-diactoros) to bridge Laravel’s Illuminate\Http\Request/Response with Psr\Http\Message.
    • Service Container: PSR-15 middleware must be resolvable via Laravel’s container (e.g., type-hinted or tagged bindings).
  • Recommended Stack Additions:
    // composer.json
    {
      "require": {
        "laminas/laminas-diactoros": "^2.10",  // PSR-7 implementation
        "equip/dispatch": "^1.0",              // The middleware dispatcher
        "php-http/message-factory": "^1.0"     // Optional: for PSR-7 factory
      }
    }
    

Migration Path

  1. Phase 1: Proof of Concept

    • Create a PSR-15 middleware adapter for Laravel:
      // app/Middleware/Psr15Adapter.php
      namespace App\Middleware;
      use Psr\Http\Message\ResponseInterface;
      use Psr\Http\Message\ServerRequestInterface;
      use Illuminate\Http\Request;
      use Illuminate\Http\Response;
      
      class Psr15Adapter implements \Psr\Http\Server\MiddlewareInterface {
          public function __construct(private \Closure $laravelMiddleware) {}
      
          public function process(ServerRequestInterface $request, \Psr\Http\Server\RequestHandlerInterface $handler): ResponseInterface {
              $laravelRequest = Request::createFromBase($request);
              $laravelResponse = $this->laravelMiddleware($laravelRequest);
              return new \Laminas\Diactoros\Response($laravelResponse->getStatusCode(), [], $laravelResponse->getContent());
          }
      }
      
    • Test with a simple PSR-15 middleware (e.g., logging).
  2. Phase 2: Dispatcher Integration

    • Bind the dispatcher to Laravel’s container:
      // app/Providers/AppServiceProvider.php
      public function register() {
          $this->app->singleton(\Equip\Dispatch\MiddlewareDispatcher::class, function ($app) {
              return new \Equip\Dispatch\MiddlewareDispatcher(
                  new \Laminas\Diactoros\ServerRequestFactory(),
                  new \Laminas\Diactoros\ResponseFactory()
              );
          });
      }
      
    • Register a facade or helper for dynamic dispatch:
      // app/Helpers/MiddlewareDispatcher.php
      use Equip\Dispatch\MiddlewareDispatcher;
      use Illuminate\Support\Facades\Facade;
      
      class MiddlewareDispatcherFacade extends Facade {
          protected static function getFacadeAccessor() { return MiddlewareDispatcher::class; }
      }
      
  3. Phase 3: Route-Level Integration

    • Use the dispatcher in Kernel.php or route middleware:
      // routes/web.php
      Route::get('/dynamic-middleware', function () {
          return response()->json(['message' => 'Success']);
      })->middleware(function ($request, $next) {
          $dispatcher = app(MiddlewareDispatcher::class);
          $psrRequest = \Laminas\Diactoros\ServerRequestFactory::fromGlobals();
          $psrResponse = $dispatcher->dispatch($psrRequest, new class implements \Psr\Http\Server\RequestHandlerInterface {
              public function handle(\Psr\Http\Message\ServerRequestInterface $request): \Psr\Http\Message\ResponseInterface {
                  return new \Laminas\Diactoros\Response();
              }
          });
          return new Response($psrResponse->getBody(), $psrResponse->getStatusCode());
      });
      

Compatibility

  • Laravel Versions:
    • Tested on Laravel 8+ (PSR-15 adapters may need adjustments for older versions).
    • Laravel 9/10: Native PSR-15 support (via symfony/http-foundation) reduces adapter complexity.
  • Middleware Types:
    • Supported: PSR-15 middleware, Laravel middleware (via adapter), Closures.
    • Unsupported: Middleware requiring Illuminate dependencies (e.g., Authenticate, VerifyCsrfToken) unless wrapped.
  • Edge Cases:
    • Middleware Short-Circuiting: PSR-15 middleware must respect Laravel’s $next pattern.
    • Session/Flash Data: PSR-7 requests/responses lack Laravel’s session bag; require manual hydration.

Sequencing

  1. Adopt PSR-7/PSR-15 Adapters (if not already using them).
  2. Implement Middleware Bridge (adapter layer).
  3. Integrate Dispatcher into Laravel’s container.
  4. Test Dynamic Dispatch in a non-critical route.
  5. Gradually Replace Static Middleware with dynamic dispatch where needed.
  6. Optimize based on benchmarks (e.g., cache PSR-15 middleware instances).

Operational Impact

Maintenance

  • Dependency Management:
    • PSR-1
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.
iio/libmergepdf
redaxo/project
zatona-eg/zatona-eg-api
patrickbussmann/oauth2-apple
3brs/enterprise-security-bundle
ardenexal/fhir-models
ardenexal/fhir-validation
dpfx/laravel-livewire-wizards
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
crudly/encrypted
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony