minte9
LearnRemember / PHP



Middleware

 
/**
 * 
 * The Middleware is a function that modifies the request 
 * before passing it to the next function.
 * 
 * Here is a simple example with plain PHP.
 */

session_start();

// Middleware function to set the username
function authSessionMiddleware($next) {
    if (!isset($_SESSION['username'])) {
        $_SESSION['username'] = 'Guest';
    }

    // Call the next function in the pipeline
    $next();
}

// Application logic after middleware runs
function app() {
    echo "Welcome, " . $_SESSION['username'] . "!" . PHP_EOL;
}

// Execute middleware and the process the request
authSessionMiddleware('app');

/**
 * Wecome, Guest!
 */

Using composer

 
/**
 * Real-life example of using middleware.
 * It is similar to what you'd see in frameworks like Laravel or Slim.
 * 
 * composer init
 *
 * myapp/
 *      composer.json 
 *      public/
 *          index.php
 *      src/
    *      Middleware/
    *          MiddlewareInterface.php
    *          SessionMiddleware.php
 *      vendor/  
 * 
 * composer dump-autoload
 */


require __DIR__ . '/../vendor/autoload.php';

use App\Middleware\SessionMiddleware;

// Simulate a request
$request = $_GET;

// Run the middleware
$md = new SessionMiddleware($request);
$md->handle($request);

// Display the session username
echo "Welcome, " . $_SESSION['username'] . "!". PHP_EOL;

/**
 * php public/index.php
 * 
 * Welcome, Guest!
 */
composer.json
 
{
    "name": "middleware/my_app",
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    },
    "require": {}
}
Middleware Interface
 
namespace App\Middleware;

interface MiddlewareInterface {
    public function handle($request); 
}
Session Implementation
 
namespace App\Middleware;

use App\Logger;

class SessionMiddleware implements MiddlewareInterface {
    public function handle($request) {
        session_start();

        if (!isset($_SESSION['username'])) {
            $_SESSION['username'] = 'Guest';
        }

        return $request;
    }
}

Dependency Injection

 
/**
 * The $request parameter is not injected into the middleware.
 * It is just passing data for processing.
 * The middleware doesn't onw the $request.
 * 
 * Here is an example of injecting a dependency into the middleware.
 * 
 * myapp/
 *      composer.json 
 *      public/
 *          DI_index.php
 *      src/
    *      Middleware/
    *      Logger.php
 *      vendor/  
 */


require __DIR__ . '/../vendor/autoload.php';

use App\Middleware\SessionMiddleware2;
use App\Logger;

// Simulate a request
$request = $_GET;

// Create dependency
$logger = new Logger();

// Run the middleware
$md = new SessionMiddleware2($logger);
$md->handle($request);

// Display the session username
echo "Welcome, " . $_SESSION['username'] . "!". PHP_EOL;

/**
 * php public/DI_index.php
 * 
 * [LOG]: Session started with default user: Guest
 * Welcome, Guest!
 */
Dependency
 
namespace App;

class Logger {
    public function log($message) {
        echo "[LOG]: " . $message . PHP_EOL;
    }
}
Middleware with dependency
 
namespace App\Middleware;

use App\Logger;

class SessionMiddleware2 implements MiddlewareInterface {
    protected $logger;

    public function __construct($logger)
    {
        $this->logger = $logger;
    }

    public function handle($request) {
        session_start();

        if (!isset($_SESSION['username'])) {
            $_SESSION['username'] = 'Guest';
            $this->logger->log("Session started with default user: Guest");
        }

        return $request;
    }
}



  Last update: 6 days ago