gnatsnapper/altorouter-middleware

A PSR-15 Middleware to allow the use of the venerable AltoRouter in Middleware-based PHP applications

v0.0.2 2020-08-14 07:42 UTC

This package is auto-updated.

Last update: 2022-06-14 12:03:28 UTC


README

Build Status PHP Composer

AltoRouter Middleware

Install

composer require gnatsnapper/altorouter-middleware

Usage

This class simply extends the venerable AltoRouter class to allow use as a router/dispatcher. If a route is not found the request is passed to the next middleware. If a route is mapped the AltoRouter will produce a response, therefore the route must be a callable returning an object implementing Psr\Http\Message\ResponseInterface.

$altorouter = new AltoRouterMiddleware();

//map array of routes

$altorouter->addRoutes(
[
    [
        'GET',
        '/',
        function () {
             $r = new Response();
             $r->getBody()->write('home');
             return $r;
        }
    ],
    [
        'GET',
        '/users',
        function () {
             $r = new Response();
             $r->getBody()->write('users');
             return $r;
        }
    ]

]
);

//or map single route

$altorouter->map(
        'GET',
        '/admin',
        function () {
             $r = new Response();
             $r->getBody()->write('admin');
             return $r;
        }
    );

Then add this middleware to the applications middleware pipeline.