ingenioz-it/router

A PHP router

v2.0.2 2024-04-20 21:45 UTC

This package is auto-updated.

Last update: 2024-04-20 21:52:58 UTC


README

A PHP Router.

Disclaimer

In order to ensure that this package is easy to integrate into your app, it is built around the PHP Standard Recommendations : it takes in a PSR-7 Server Request and returns a PSR-7 Response. It also uses a PSR-11 Container (such as EDICT) to resolve the route handlers.

It is inspired by routers from well-known frameworks (did anyone say Laravel ?) aswell as some home-made routers used internally by some major companies.

It is build with quality in mind : readability, immutability, no global states, 100% code coverage, 100% mutation testing score, and validation from various static analysis tools at the highest level.

About

Info Value
Latest release Packagist Version
Requires PHP from Packagist
License Packagist
Unit tests tests
Code coverage Code Coverage
Code quality code-quality
Quality tested with phpunit, phan, psalm, phpcs, phpstan, phpmd, infection, rector

Installation

composer require ingenioz-it/router

Documentation

Overview

Here is the whole process of using this router :

  • Create your routes
  • Instantiate the router
  • Handle the request:
use IngeniozIT\Router\RouteGroup;
use IngeniozIT\Router\Route;
use IngeniozIT\Router\Router;

// Create your routes

$routes = new RouteGroup([
    Route::get('/hello', fn() => new Response('Hello, world!')),
    Route::get('/bye', fn() => new Response('Goodbye, world!')),
]);

// Instantiate the router

/** @var Psr\Container\ContainerInterface $container */
$container = new Container();
$router = new Router($routes, $container);

// Handle the request

/** @var Psr\Http\Message\ServerRequestInterface $request */
$request = new ServerRequest();
/** @var Psr\Http\Message\ResponseInterface $response */
$response = $router->handle($request);

Basic routing

The simplest route consists of a path and a handler.

The path is a string, and the handler is a callable that will be executed when the route is matched. The handler must return a PSR-7 ResponseInterface.

Route::get('/hello', fn() => new Response('Hello, world!'));

Organizing routes

Route groups are used to contain routes definitions.
They also allows you to visually organize your routes according to your application's logic.

This is useful when you want to apply the same conditions, middlewares, or attributes to several routes at once (as we will see later).

new RouteGroup([
    Route::get('/hello', fn() => new Response('Hello, world!')),
    Route::get('/bye', fn() => new Response('Goodbye, world!')),
]);

Route groups can be nested to create a hierarchy of routes that will inherit everything from their parent groups.

new RouteGroup([
    Route::get('/', fn() => new Response('Welcome !')),
    new RouteGroup([
        Route::get('/hello', fn() => new Response('Hello, world!')),
        Route::get('/hello-again', fn() => new Response('Hello again, world!')),
    ]),
    Route::get('/bye', fn() => new Response('Goodbye, world!')),
]);

HTTP methods

You can specify the HTTP method that the route should match:

Route::get('/hello', MyHandler::class);
Route::post('/hello', MyHandler::class);
Route::put('/hello', MyHandler::class);
Route::patch('/hello', MyHandler::class);
Route::delete('/hello', MyHandler::class);
Route::options('/hello', MyHandler::class);

If you want a route to match multiple HTTP methods, you can use the some method:

Route::some(['GET', 'POST'], '/hello', MyHandler::class);

You can also use the any method to match all HTTP methods:

Route::any('/hello', MyHandler::class);

Path parameters

Basic usage

You can define route parameters by using the {} syntax in the route path.

Route::get('/hello/{name}', MyHandler::class);

The matched parameters will be available in the request attributes.

class MyHandler implements RequestHandlerInterface
{
    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        $name = $request->getAttribute('name');
        return new Response("Hello, $name!");
    }
}

Route::get('/hello/{name}', MyHandler::class);

Custom parameter patterns

By default, the parameters are matched by the [^/]+ regex (any characters that are not a /).

You can specify a custom pattern by using the where parameter:

// This route will only match if the name contains only letters
Route::get('/hello/{name}', MyHandler::class, where: ['name' => '[a-zA-Z]+']);

Custom parameter patterns in a group

Parameters patterns can also be defined globally for all routes inside a group:

$routes = new RouteGroup(
    [
        Route::get('/hello/{name}', MyHandler::class),
        Route::get('/bye/{name}', MyOtherHandler::class),
    ],
    where: ['name' => '[a-zA-Z]+'],
);

Route handlers

Closures

The simplest way to define a route handler is to use a closure.
The closure must return a PSR-7 ResponseInterface.

Route::get('/hello', fn() => new Response('Hello, world!'));

Closures can take in parameters: the request and a request handler (the router itself).

Route::get('/hello', function (ServerRequestInterface $request) {
    return new Response('Hello, world!');
});

Route::get('/hello', function (ServerRequestInterface $request, RequestHandlerInterface $router) {
    return new Response('Hello, world!');
});

RequestHandlerInterface

A route handler can be a callable, but it can also be a PSR RequestHandlerInterface.

use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Server\ServerRequestInterface;
use Psr\Http\Server\ResponseInterface;

class MyHandler implements RequestHandlerInterface
{
    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        return new Response('Hello, world!');
    }
}

Route::get('/hello', new MyHandler());

MiddlewareInterface

Sometimes, you might want a handler to be able to "refuse" to handle the request, and pass it to the next handler in the chain.

This is done by using a PSR MiddlewareInterface as a route handler :

use Psr\Http\Server\MiddlewareInterface;

class MyHandler implements MiddlewareInterface
{
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        if (resourceDoesNotExist()) {
            // We don't want this handler to continue processing the request,
            // so we pass the responsability to the next handler
            return $handler->handle($request);
        }

        /* ... */
    }
}

$routes = new RouteGroup([
    // This handler will be called first
    Route::get('/{ressource}', fn() => new MyHandler()),
    // This handler will be called next
    Route::get('/{ressource}', fn() => new Response('Hello, world!')),
]);

Dependency injection

Instead of using a closure or a class instance, your handler can be a class name. The router will then resolve the class using the PSR container you injected into the router.

Route::get('/hello', MyHandler::class);

The router will resolve this handler by calling get(MyHandler::class) on the container. This means that you can use any value that the container can resolve into a valid route handler.

Additional attributes

You can add additional attributes to a route by using the with method.
Just like path parameters, these attributes will be available in the request attributes.

class MyHandler implements RequestHandlerInterface
{
    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        $name = $request->getAttribute('name');
        return new Response("Hello, $name!");
    }
}

// Notice there is no name parameter in the route path
Route::get('/hello', MyHandler::class, with: ['name' => 'world']);

Attributes can also be defined globally for all the routes inside a group:

$routes = new RouteGroup(
    [
        Route::get('/hello', MyHandler::class),
        Route::get('/bye', MyOtherHandler::class),
    ],
    with: ['name' => 'world'],
);

Middlewares

Middlewares are classes that can modify the request and/or the response before and after the route handler is called.

They can be applied to a route group.

$routes = new RouteGroup(
    [
        Route::get('/hello', MyHandler::class),
    ],
    middlewares: [
        MyMiddleware::class,
        MyOtherMiddleware::class,
    ],
);

The middleware class must implement the PSR \Psr\Http\Server\MiddlewareInterface interface.

Conditions

Conditions are callables that will determine if a route group should be parsed.

// This one will be parsed
$routes = new RouteGroup(
    [
        Route::get('/hello', MyHandler::class),
    ],
    conditions: [
        fn(ServerRequestInterface $request) => true,
    ],
);

// This one will NOT be parsed
$routes = new RouteGroup(
    [
        Route::get('/hello', MyHandler::class),
    ],
    conditions: [
        fn(ServerRequestInterface $request) => false,
    ],
);

Additionally, conditions can return an array of attributes that will be added to the request attributes.

class MyHandler implements RequestHandlerInterface
{
    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        $name = $request->getAttribute('name');
        return new Response("Hello, $name!");
    }
}

$routes = new RouteGroup(
    [
        Route::get('/hello', MyHandler::class),
    ],
    conditions: [
        // This condition will add the 'name' attribute to the request
        fn(ServerRequestInterface $request) => ['name' => 'world'],
    ],
);

If a condition returns an array, it is assumed that the route group should be parsed.

If any condition returns false, the route group will not be parsed:

// This one will NOT be parsed
$routes = new RouteGroup(
    [
        Route::get('/hello', MyHandler::class),
    ],
    conditions: [
        fn(ServerRequestInterface $request) => true,
        fn(ServerRequestInterface $request) => false,
    ],
);

Naming routes

Routes can be named.

Route::get('/hello', MyHandler::class, name: 'hello_route');

Using the router, you can then generate the path to a named route:

$router->pathTo('hello_route'); // Will return '/hello'

If a route has parameters, you can pass them as the second argument:

Route::get('/hello/{name}', MyHandler::class, name: 'hello_route');

$router->pathTo('hello_route', ['name' => 'world']); // Will return '/hello/world'

Error handling

This router uses custom exceptions to handle errors.

Here is the inheritance tree of those exceptions:

  • IngeniozIT\Router\RouterException (interface): the base exception, all other exceptions inherit from this one
    • IngeniozIT\Router\EmptyRouteStack: thrown when no route has been matched by the router
    • IngeniozIT\Router\Route\RouteException: (interface) the base exception for route errors
      • IngeniozIT\Router\Route\Exception\InvalidRouteHandler: thrown when the route handler is not a valid request handler
      • IngeniozIT\Router\Route\Exception\InvalidRouteResponse: thrown when the route handler does not return a PSR-7 ResponseInterface
      • IngeniozIT\Router\Route\Exception\RouteNotFound: thrown when calling $router->pathTo with a route name that does not exist
      • IngeniozIT\Router\Route\Exception\InvalidRouteParameter: thrown when calling $router->pathTo with invalid parameters
      • IngeniozIT\Router\Route\Exception\MissingRouteParameters: thrown when calling $router->pathTo with missing parameters
    • IngeniozIT\Router\Middleware\MiddlewareException: (interface) the base exception for middleware errors
      • IngeniozIT\Router\Middleware\Exception\InvalidMiddlewareHandler: thrown when a middleware is not a valid middleware handler
      • IngeniozIT\Router\Middleware\Exception\InvalidMiddlewareResponse: thrown when a middleware does not return a PSR-7 ResponseInterface
    • IngeniozIT\Router\Condition\ConditionException: (interface) the base exception for condition errors
      • IngeniozIT\Router\Condition\Exception\InvalidConditionHandler: thrown when a condition is not a valid condition handler
      • IngeniozIT\Router\Condition\Exception\InvalidConditionResponse: thrown when a condition does not return a valid response