PHP code example of matthiasmullie / router

1. Go to this page and download the library: Download matthiasmullie/router library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

matthiasmullie / router example snippets


use MatthiasMullie\Router\RequestMethods;
use MatthiasMullie\Router\Router;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7\ServerRequest;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

// create 2 example request handlers
class RouteOne implements RequestHandlerInterface
{
    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        return new Response(
            200,
            ['Content-Type' => 'application/json; charset=utf-8'],
            json_encode(['message' => 'Hello world']),
        );
    }
}
class RouteTwo implements RequestHandlerInterface
{
    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        return new Response(
            200,
            ['Content-Type' => 'text/html; charset=utf-8'],
            '<html><body><p>Hello world</p></body></html>',
        );
    }
}

// create router instance and add both routes
$this->router = new Router();
$this->router->addRoute(
    RequestMethods::GET,
    '/one',
    new RouteOne(),
);
$this->router->addRoute(
    RequestMethods::GET,
    '/two',
    new RouteTwo(),
);

// route a request, receive response from the matching request handler
$response = $router->handle(
    new ServerRequest('GET', '/one'),
);
echo $response->getBody(); // outputs: {"message":"Hello world"}

// create router instance and add an individual route
$this->router = new Router();
$this->router->addRoute(
    RequestMethods::GET,
    '/one', // maps to /one
    new RouteOne(),
);

// then 2 more routes with a shared prefix 
$group = $this->router->addGroup('/prefix');
$group->addRoute(
    RequestMethods::GET,
    '/two', // maps to /prefix/two
    new RouteTwo(),
);
$group->addRoute(
    RequestMethods::GET,
    '/three', // maps to /prefix/three
    new RouteThree(),
);

class Middleware implements MiddlewareInterface {
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // execute something before handling the request,
        // or manipulate the request object
        $request = $request->withAttribute('middleware', 'Hello world');

        // invoke the handler (or the next middleware, if any)
        // and retrieve the response
        $response = $handler->handle($request);

        // execute something after handling the request,
        // or manipulate the response object
        return $response->withAddedHeader('Content-Type', 'application/json; charset=utf-8);
    }
} 

// create router instance and add a route with middleware
$this->router = new Router();
$this->router
    ->addRoute(
        RequestMethods::GET,
        '/one',
        new RouteOne(),
    )
    ->addMiddleware(
        new Middleware(),
    );

// or add a group with middleware that applies to all routes within that group
$this->router
    ->addGroup('/prefix')
    ->addMiddleware(
        new Middleware(),
    )
    ->addRoute(
        RequestMethods::GET,
        '/two',
        new RouteTwo(),
    );

// or add middleware that applies to all routes
$this->router->addMiddleware(
    new Middleware(),
);

use MatthiasMullie\Router\Exception;
use MatthiasMullie\Router\ExceptionResponse;

class RouteException implements RequestHandlerInterface
{
    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        throw new Exception('Not Implemented', 501);
    }
}

$this->router = new Router(new ExceptionResponse(new Response()));
$this->router->addRoute(
    RequestMethods::GET,
    '/exception',
    new RouteException(),
);

$response = $router->handle(
    new ServerRequest('GET', '/exception'),
);
// $response now