Middleware in PHP-Fast allows you to filter HTTP requests entering your application. This can be useful for tasks such as user authentication, input validation, and permission checks before the request reaches the controller.
Create Middleware
All middleware classes should be placed in the application/Middleware directory. A middleware class contains a handle() method, which will be executed when the middleware is applied to a route or controller.
To ensure only authenticated users can access certain routes, let's create a simple authentication middleware.
Steps to Create AuthMiddleware
Navigate to application/Middleware/.
Create a new file named AuthMiddleware.php.
Add the following code to handle authentication:
<?phpnamespaceApp\Middleware;classAuthMiddleware{publicfunctionhandle($request,$next){ // Check if the user is logged inif(!isset($_SESSION['user'])){echo"Unauthorized access!";exit;} // Proceed to the next middleware or controllerreturn$next($request);}}
Using Middleware in Route
To apply middleware to a route, include the middleware class name as an array in the route definition inside application/Routes/web.php or application/Routes/api.php.
Example:Adding AuthMiddleware to a Route in web.php
More Example
As the same AuthMiddleware, you can create a PermissionMiddleware to manage access control for different parts of your application.
Create a new file in application/Middleware/ named PermissionMiddleware.php.
Add the following code to handle authentication:
Add middleware to a route and pass the necessary permissions:
<?php
namespace App\Middleware;
class PermissionMiddleware
{
public function handle($request, $next, $permissions = [])
{
// Retrieve the user's permissions from the session
$userPermissions = $_SESSION['user_permissions'] ?? [];
// Check if the user has the required permissions
foreach ($permissions as $permission) {
if (!in_array($permission, $userPermissions)) {
echo "You have no permission to access this page!";
exit;
}
}
// Proceed to the next middleware or controller
return $next($request);
}
}