idiosyncratic/http-router

A lightweight PSR-15 based HTTP router implementation

0.5.1 2019-11-30 05:42 UTC

This package is auto-updated.

Last update: 2024-03-29 04:18:26 UTC


README

A lightweight PSR-15 HTTP router implementation.

Installation

Use Composer:

composer require idiosyncratic/http-router

Usage

Idiosyncratic\Http\Router\Router implementing the PSR-15 Psr\Http\Server\RequestHandlerInterface is the main class. It has two dependencies:

  • An implementation of Idiosyncratic\Http\Router\RouteCollection, a collection of routes implementing a single method:
    /**
     * @throws Idiosyncratic\Http\Exception\Client\NotFound
     * @throws Idiosyncratic\Http\Exception\Client\MethodNotAllowed
     */
    public function findRoute(ServerRequestInterface $request) : Idiosyncratic\Http\Router\Route;
  • Psr\Container\ContainerInterface, responsible for retrieving the handler for the matched route.

Also included is Idiosyncratic\Http\Router\RouteGroup, a basic implementation of the RouteCollection interface based on FastRoute. The interface for defining routes is nearly identical to FastRoute's, with two notable exceptions:

  • The argument order for RouteGroup::addRoute is different. Route methods are defined last as string parameters.
  • The route handler must be the name of a class implementing Psr\Http\Server\RequestHandlerInterface.

Basic usage of the library (using the PHP League Container):

$container = new League\Container\Container();

$container->add(ServerRequestInterfaceImplementation::class);

$routes = new Idiosyncratic\Http\Router\RouteGroup();

$routes->addRoute('/hello', ServerRequestInterfaceImplementation::class, 'GET', 'POST');

$router = new Idiosyncratic\Http\Router\Router($routes, $container);

// Create instance of Psr\Http\Message\ServerRequestInterface...

$response = $router->handle($serverRequest);