REMEMBER PHP

MINTE9
2REMEMBER




Last update:   23-07-2021

Middleware

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.

Routing

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
... 2 more rows
˄˄˄
We define the route for our Hello World example. For this to work we also need to make HelloWorld an invokable class.
 CodeCopy
// /public/index.php

declare(strict_types=1);

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);
$requestHandler->handle(ServerRequestFactory::fromGlobals());
... 14 more rows
˄˄˄
 CodeCopy
// /src/HelloWorld.php

declare(strict_types=1);

namespace ExampleApp;

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

}
... 8 more rows
˄˄˄
 
// http://localhost:8080/public/hello
    // Hello World, from routes!

Questions    
No. 84   Custom
CARD
83
96

        A B C D E F
🔔
1/1