Middleware
Middleware allows you to run code before a request is completed. You can modify the response, rewrite, redirect, update headers, or respond directly.
Middleware
Middleware allows you to run code before a request is completed. Then, based on the incoming request, you can modify the response by rewriting, redirecting, modifying the request or response headers, or responding directly.
Use Cases
Integrating Middleware into your application can lead to significant improvements in performance, security, and user experience. Some common scenarios where Middleware is particularly effective include:
- Authentication – Verify user credentials before granting access.
- Authorization – Check roles and permissions before accessing resources.
- Logging – Log requests, responses, and errors for debugging and monitoring.
- Server-Side Redirects – Redirect users based on conditions (locale, role, etc.).
- Caching – Cache responses to improve performance and reduce load.
- Rate Limiting – Limit the number of requests by IP to prevent abuse.
- Compression – Compress responses to reduce bandwidth and improve load times.
Recognizing situations where middleware may not be optimal is just as important:
- Heavy Processing – Avoid expensive operations that slow requests.
- Blocking – Middleware that blocks execution may degrade performance.
- Over-Engineering – Keep middleware simple and focused.
- Security Risks – Avoid vulnerabilities such as injection attacks.
- Direct Database Operations – DB queries should be in route handlers or utilities.
Convention
Prisma PHP follows a convention-based approach to Middleware, where each Middleware is defined as a
class with a specific structure. Middleware classes should be stored in the
Lib/Middleware directory and registered in the
bootstrap.php file.
Here is an example of how to register Middleware in bootstrap.php:
<?php
use Lib\Middleware\AuthMiddleware;
function determineContentToInclude()
{
/**
* ============ URI Handling ============
* The $requestUri variable now contains the full URI including query parameters.
* Examples:
* - Home page: '/'
* - Dynamic routes with parameters (e.g., '/dashboard?v=2' or '/profile?id=5')
* ======================================
*/
$requestUri = $_SERVER['REQUEST_URI'];
$requestUri = empty($_SERVER['SCRIPT_URL']) ? uriExtractor($requestUri) : $requestUri;
/**
* ============ URI Path Handling ============
* The $uri variable now contains the URI path without query parameters and without the leading slash.
* Examples:
* - Home page: '' (empty string)
* - Dynamic routes (e.g., '/dashboard?v=2' or '/profile?id=5') -> Only the path part is returned (e.g., 'dashboard' or 'profile')
* ============================================
*/
$scriptUrl = explode('?', $requestUri, 2)[0];
$pathname = $_SERVER['SCRIPT_URL'] ?? $scriptUrl;
$pathname = ltrim($pathname, '/');
$baseDir = APP_PATH;
$includePath = '';
$layoutsToInclude = [];
/**
* ============ Middleware Management ============
* AuthMiddleware is invoked to handle authentication logic for the current route ($pathname).
* ================================================
*/
AuthMiddleware::handle($pathname);
// Place your custom middleware here
/**
* ============ End of Middleware Management ======
* ================================================
*/
}
?>