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

Request Handler Laravel Package

middlewares/request-handler

PSR-15/PSR-7 request handler middleware for PHP. Build a flexible pipeline that routes an incoming ServerRequest to your handler stack, with clean delegation and composable middlewares—ideal for frameworks or custom apps needing standard request processing.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require middlewares/request-handler
    

    Add to composer.json under require-dev if using for testing.

  2. Basic Usage Register the middleware in app/Http/Kernel.php:

    protected $middleware = [
        \Middlewares\RequestHandler::class,
    ];
    
  3. First Use Case Define a handler class (e.g., app/Handlers/ValidateRequest.php):

    namespace App\Handlers;
    
    use Middlewares\RequestHandler\HandlerInterface;
    use Psr\Http\Message\ResponseInterface;
    use Psr\Http\Message\ServerRequestInterface;
    
    class ValidateRequest implements HandlerInterface
    {
        public function __invoke(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
        {
            if (!$request->getAttribute('valid')) {
                return $response->withStatus(400);
            }
            return $response;
        }
    }
    

    Bind the handler in AppServiceProvider:

    public function boot()
    {
        $this->app->bind(\Middlewares\RequestHandler\HandlerInterface::class, \App\Handlers\ValidateRequest::class);
    }
    

Implementation Patterns

Core Workflows

  1. Chaining Handlers Use middleware groups or stack handlers via HandlerInterface:

    // app/Handlers/ChainHandlers.php
    class ChainHandlers implements HandlerInterface
    {
        public function __invoke(ServerRequestInterface $request, ResponseInterface $response)
        {
            $handler = $this->app->make(HandlerInterface::class);
            return $handler($request, $response);
        }
    }
    
  2. Conditional Execution Skip handlers based on request attributes or routes:

    if (!$request->getAttribute('skip_validation')) {
        return $handler($request, $response);
    }
    
  3. Dependency Injection Inject services into handlers via Laravel’s container:

    class AuthHandler implements HandlerInterface
    {
        protected $auth;
    
        public function __construct(AuthManager $auth)
        {
            $this->auth = $auth;
        }
    
        public function __invoke(ServerRequestInterface $request, ResponseInterface $response)
        {
            if (!$this->auth->check()) {
                return $response->withStatus(401);
            }
            return $response;
        }
    }
    

Integration Tips

  • Laravel Routes: Use middleware in route definitions:
    Route::middleware(RequestHandler::class)->group(function () {
        // Routes here
    });
    
  • Testing: Mock handlers in PHPUnit:
    $this->app->instance(HandlerInterface::class, MockHandler::class);
    
  • Performance: Cache handler instances if stateless (e.g., validation).

Gotchas and Tips

Pitfalls

  1. Circular Dependencies Avoid binding handlers that depend on other handlers in the same stack. Use explicit service binding instead.

  2. Request/Response Mutations Handlers may unintentionally modify $request or $response. Document expectations clearly:

    // Example: Do NOT modify $request->getParsedBody() if downstream handlers rely on it.
    
  3. Middleware Order The package executes handlers after Laravel’s middleware. Reorder in Kernel.php if needed:

    protected $middlewareGroups = [
        'web' => [
            // Custom middleware first...
            \Middlewares\RequestHandler::class,
        ],
    ];
    
  4. PSR-15 Compliance Ensure responses adhere to PSR-7 (e.g., withStatus() over setStatusCode()).

Debugging

  • Handler Not Triggering? Verify the handler is bound and no exceptions are silently caught. Use:
    try {
        $handler($request, $response);
    } catch (\Throwable $e) {
        report($e); // Log via Laravel's error handler
    }
    
  • Response Overrides If a handler returns a response, subsequent handlers won’t execute. Use next($request) pattern if chaining.

Extension Points

  1. Custom Handler Resolvers Override the default resolver via a service provider:
    $this->app->bind(
        \Middlewares\RequestHandler\HandlerResolver::class,
        \App\Handlers\CustomResolver::class
    );
    
  2. Handler Metadata Tag handlers for dynamic routing (e.g., #[Handler(priority: 10)] via attributes).
  3. Async Support Wrap handlers in Laravel\Bus\Queueable for background processing:
    class AsyncHandler implements HandlerInterface, ShouldQueue
    {
        // ...
    }
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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