Skip to content

Conversation

@rakibdevs
Copy link

Added Conditional Middleware, a new PSR-15 compliant middleware that enables conditional execution of middleware based on request properties.

Use Cases

  1. Path-based Middleware Application
// Authentication only for admin routes
$app->add(
    ConditionalMiddleware::forPath($authMiddleware, '/admin')
);
  1. Method-based Middleware Application
// CSRF protection only for state-changing methods
$app->add(
    ConditionalMiddleware::forMethods($csrfMiddleware, ['POST', 'PUT', 'PATCH', 'DELETE'])
);
  1. Combined Conditions
// Rate limiting only for API POST/PUT requests
$app->add(
    ConditionalMiddleware::forPathAndMethods(
        $rateLimitMiddleware,
        '/api',
        ['POST', 'PUT']
    )
);
  1. Attribute-based Conditions
// Audit logging only for authenticated users
$app->add(
    new ConditionalMiddleware(
        $auditMiddleware,
        fn($request) => $request->getAttribute('user') !== null
    )
);
  1. Complex Business Logic
// Apply middleware based on multiple criteria
$app->add(
    new ConditionalMiddleware(
        $specialMiddleware,
        fn($request) => 
            $request->getAttribute('subscription') === 'premium' &&
            !str_starts_with($request->getUri()->getPath(), '/public')
    )
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant