Middleware ni code inayofanya pre-processing au post-processing ya requests:

Validate user authentication

Restrict access based on roles

Log requests or perform security checks

Goal: Handle requests before they reach controllers for security and modularity.

⚙️ 2. Project Folder Structure
project_root/

├── app/
│ ├── controllers/
│ │ └── DashboardController.php
│ └── middleware/
│ └── AuthMiddleware.php
├── core/
│ └── Controller.php
├── public/
│ └── index.php
└── config/
└── config.php

🧩 3. Example Middleware (app/middleware/AuthMiddleware.php)
<?php
class AuthMiddleware {
public static function handle(){
session_start();

if(!isset($_SESSION['user_id'])){
// User not logged in
header("Location: login.php");
exit();
}

// Optional: Role-based check
if(isset($_SESSION['role']) && $_SESSION['role'] !== 'Admin'){
die("❌ Access denied. Admins only.");
}
}
}


handle() method checks session

Redirects unauthenticated users to login

Optionally checks user role

🧩 4. Using Middleware in Controller (app/controllers/DashboardController.php)
<?php
require_once '../app/middleware/AuthMiddleware.php';

class DashboardController extends Controller {
public function index(){
// Apply middleware
AuthMiddleware::handle();

// Protected content
echo "Welcome ".$_SESSION['username']." to the admin dashboard!";
}
}

🧩 5. Applying Middleware Globally (Front Controller public/index.php)
<?php
spl_autoload_register(function($class){
$paths = ['../app/controllers/', '../app/models/', '../core/', '../app/middleware/'];
foreach($paths as $path){
$file = $path . $class . '.php';
if(file_exists($file)){
require_once $file;
return;
}
}
});

// Example: protect all dashboard requests
if(isset($_GET['url']) && strpos($_GET['url'], 'dashboard') === 0){
AuthMiddleware::handle();
}

// Continue routing logic...

🔑 6. Best Practices

Keep middleware modular – one middleware per responsibility (auth, logging, etc.)

Use for authentication & authorization – before controller logic

Chain multiple middleware – e.g., auth → role check → logging

Avoid putting business logic in middleware – only pre/post request checks

Combine with sessions, CSRF, and input validation – for full security

✅ 7. Hitimisho

Middleware makes PHP applications secure, modular, and maintainable

Centralizes request checks and prevents code duplication

Works seamlessly with MVC architecture, routing, and RBAC

🔗 Tembelea:

👉 https://www.faulink.com/

Kwa mafunzo zaidi ya PHP, middleware, na security best practices.