An application is like an onion with different layers. The middleware is each layer receiving the request, do something with it, and then pass it to the next layer or send it back to the layer above it.


A router uses information from the request and figure out which class to handle. We'll use a popular router library (fast-route). We'll also need a middleware dispatcher (relay). PSR-15 spec requires implementations to pass along PSR-7 (laminas-diactoros).
// use setup from previous Dependencies Injection page

cd /var/www/php/noframework
composer require relay/relay
composer require laminas/laminas-diactoros
composer require middlewares/fast-route middlewares/request-handler
We define the route for our Hello World example. For this to work we also need to make HelloWorld an invokable class.
// /public/index.php


use ExampleApp\HelloWorld;

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

use Relay\Relay; // middleware dispatcher
use Laminas\Diactoros\ServerRequestFactory; // PSR-7 compatibility
use Middlewares\FastRoute; // middleware
use Middlewares\RequestHandler;
use FastRoute\RouteCollector; // router
use function FastRoute\simpleDispatcher;

$routes = simpleDispatcher(function(RouteCollector $r) {
    $r->get('/public/hello', HelloWorld::class);

$middlewareQueue[] = new FastRoute($routes);
$middlewareQueue[] = new RequestHandler();

$requestHandler = new Relay($middlewareQueue);
// /src/HelloWorld.php


namespace ExampleApp;

class HelloWorld
    public function __invoke() : void
        echo 'Hello World, from routes';

// http://localhost:8080/public/hello
    // Hello World, from routes!

  Last update: 233 days ago