2017 © Pedro Peláez
 

library router

Regexp based Router, easy to use and with a rich feature set

image

quimcalpe/router

Regexp based Router, easy to use and with a rich feature set

  • Thursday, October 19, 2017
  • by quimcalpe
  • Repository
  • 2 Watchers
  • 1 Stars
  • 3,470 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 1 Forks
  • 0 Open issues
  • 16 Versions
  • 4 % Grown

The README.md

quimcalpe/router

Version License Build Status Code Coverage Scrutinizer Code Quality, (*1)

Regexp based Router, easy to use and with a rich feature set. It includes various built-in dispatchers, and we also provide an interface to develop fully customized dispatchers for your project., (*2)

Install

Via Composer, (*3)

``` bash $ composer require quimcalpe/router, (*4)


## Requirements The following versions of PHP are supported by this version. * PHP 8.1 ## Basic Usage ```php // Require composer autoloader require __DIR__ . '/vendor/autoload.php'; use QuimCalpe\Router\Router; use QuimCalpe\Router\Dispatcher\SimpleDispatcher; // Create Router instance $router = new Router(); // Define routes, last parameter defining route name is optional $router->addRoute('GET', '/users', 'Quimi\Controllers\UserController', 'user_list'); $router->addRoute('GET', '/users/edit/{id:number}', 'Quimi\Controllers\UserController::edit', 'user_edit'); $router->addRoute(['POST', 'DELETE'], '/users/remove/{id:number}', 'Quimi\Controllers\UserController::remove', 'user_delete'); // Sugar methods for common verbs are also available (GET, POST, PUT, DELETE...) $router->addGet('/user/{id}', 'Quimi\Controllers\UserController::show', 'user_show'); // You can also create a QuimCalpe\Router\Route\Route value object and add directly to router's `->add()` $route = new Route('GET', '/', 'Quimi\Controllers\HomeController', 'home'); $router->add($route); try { // Match routes $route = $router->parse($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI']); // Dispatch route $dispatcher = new SimpleDispatcher(); $response = $dispatcher->handle($route); } catch (QuimCalpe\Router\Exception\MethodNotAllowedException $e) { header('HTTP/1.0 405 Method Not Allowed'); // exception message contains allowed methods header('Allow: '.$e->getMessage()); } catch (QuimCalpe\Router\Exception\RouteNotFoundException $e) { header('HTTP/1.0 404 Not Found'); // not found.... }

Constructor optional Route[] parameter

You can alternatively pass an array of Route objects to Router's constructor, and routes will be created;, (*5)

use QuimCalpe\Router\Router;
use QuimCalpe\Router\Route\Route;

$routes = [
    new Route('GET', '/users', 'Quimi\Controllers\UserController', 'user_list'),
    new Route('GET', '/users/edit/{id:number}', 'Quimi\Controllers\UserController::edit', 'user_edit'),
    new Route(['POST', 'DELETE'], '/users/remove/{id:number}', 'Quimi\Controllers\UserController::remove', 'user_delete'),
]

$router = new Router($routes);

This array can be included from another file, enabling config separation in a simple way., (*6)

Route Providers

If you want to import a bunch of Routes from a specific package/namespace/bundle and you want to keep routes organized, you can use Route providers, define your provider like this:, (*7)

namespace My\Package;

use QuimCalpe\Router\Route\Route;
use QuimCalpe\Router\Route\RouteProvider;

class MyPackageRoutes implements RouteProvider
{
    public function routes(): array
    {
        return [
            new Route('GET', '/users', 'Quimi\Controllers\UserController', 'user_list'),
            new Route('GET', '/users/edit/{id:number}', 'Quimi\Controllers\UserController::edit', 'user_edit'),
            new Route(['POST', 'DELETE'], '/users/remove/{id:number}', 'Quimi\Controllers\UserController::remove', 'user_delete'),
        ];
    }
}

And then initialize the Router with:, (*8)

$router = new Router();
$router->addRouteProvider(new \My\Package\MyPackageRoutes());

Route Patterns

Basic regexp patterns are supported, some are already included:, (*9)

  • [^/]+ as default
  • 'word' => \w+
  • 'number' => \d+
  • 'slug' => [A-Za-z0-9_-]+

Patterns can be used this way:, (*10)

$router->addRoute('GET', '/users/edit/{id:number}', 'Controller::action');
$router->addRoute('GET', '/users/{name:word}', 'Controller::action');

You can define your own patterns:, (*11)

$router->addPattern("phone", "[0-9]-[0-9]{3}-[[0-9]{3}-[0-9]{4}"); // #-###-###-####
$router->addRoute("GET", "/customer/{phone:phone}", "Vendor\Package\Controller");
$parsedRoute = $router->parse("GET", "/customer/1-222-333-4444");

Wildcards

Wildcards in routes can be used with WildcardDispatcher:, (*12)

$router->addRoute('GET', '/test/{controller}/{action}/{id}', 'Vendor\Package\{controller}::{action}');
$parsedRoute = $router->parse("GET", "/test/user/edit");
$dispatcher = new WildcardDispatcher;
$response = $dispatcher->handle($parsedRoute); // => Vendor\Package\User::edit($id)

Request Response

Standard Request - Response workflow with Symfony HttpFoundation components is supported with RequestResponseDispatcher:, (*13)

use Symfony\Component\HttpFoundation\Request;
use QuimCalpe\Router\Router;
use QuimCalpe\Router\Dispatcher\RequestResponseDispatcher;

$router = new Router();
$router->addRoute('GET', '/users', 'Quimi\Controllers\UserController::index');

$request = Request::createFromGlobals();
$route = $router->parse($request->getMethod(), $request->getPathInfo());

// You can optionally modify the request object here before dispatching:
$request->attributes->set('foo', 'bar');

$dispatcher = new RequestResponseDispatcher($request);
$response = $dispatcher->handle($route);
$response->send();

PSR-7 HTTP Message

A built-in PSR7Dispatcher is available to work with PHP-FIG's PSR-7 HTTP Message standard implementations, an example using Zend Diactoros and a simple PSR-7 Response Sender would look like this:, (*14)

use QuimCalpe\Router\Router;
use QuimCalpe\Router\Route\Route;
use QuimCalpe\Router\Dispatcher\PSR7Dispatcher;
use function QuimCalpe\ResponseSender\send AS send_response;
use Zend\Diactoros\ServerRequestFactory;
use Zend\Diactoros\Response;

$router = new Router();
$router->add(new Route("GET", "/test", "ControllerFoo"));

$request = ServerRequestFactory::fromGlobals();
$route = $router->parse($request->getMethod(), $request->getUri()->getPath());

$dispatcher = new PSR7Dispatcher($request, new Response());
$response = $dispatcher->handle($route);
send_response($response);

Custom Dispatcher

You can create your custom Dispatcher, implementing DispatcherInterface:, (*15)

interface DispatcherInterface
{
    public function handle(ParsedRoute $route): mixed;
}

QuimCalpe\Router\Route\ParsedRoute is a small Value Object with controller() and params() methods already parsed by Router::parse., (*16)

Trailing slash

Default behaviour is to honour distinction between routes with and wothout trailing slashes:, (*17)

$router = new Router();
$router->addRoute('GET', '/users', 'Controller');
$router->parse('GET', '/users'); // => OK!
$router->parse('GET', '/users/'); // => NOT FOUND

You can disable this behaviour with disableTrailingSlashCheck method:, (*18)

$router = new Router();
$router->addRoute('GET', '/users', 'Controller');
$router->disableTrailingSlashCheck();
$router->parse('GET', '/users'); // => OK!
$router->parse('GET', '/users/'); // => OK!

Testing

bash $ vendor/bin/phpunit, (*19)

License

The MIT License (MIT). Please see License File for more information., (*20)

The Versions

19/10 2017

dev-master

9999999-dev https://github.com/quimcalpe/router

Regexp based Router, easy to use and with a rich feature set

  Sources   Download

MIT

The Requires

 

The Development Requires

by Quim Calpe

psr-7 route dispatcher uri

17/09 2016

1.2.1

1.2.1.0 https://github.com/quimcalpe/router

Regexp based Router, easy to use and with a rich feature set

  Sources   Download

MIT

The Requires

 

The Development Requires

by Quim Calpe

psr-7 route dispatcher uri

17/09 2016

1.2.0

1.2.0.0 https://github.com/quimcalpe/router

Regexp based Router, easy to use and with a rich feature set

  Sources   Download

MIT

The Requires

 

The Development Requires

by Quim Calpe

psr-7 route dispatcher uri

21/12 2015

1.1.0

1.1.0.0 https://github.com/quimcalpe/router

Regexp based Router, easy to use and with a rich feature set

  Sources   Download

MIT

The Requires

 

The Development Requires

by Quim Calpe

psr-7 route dispatcher uri

26/11 2015

1.0.0

1.0.0.0 https://github.com/quimcalpe/router

A simple Router and Dispatcher

  Sources   Download

MIT

The Requires

 

The Development Requires

by Quim Calpe

route

23/11 2015

0.4.0

0.4.0.0 https://github.com/quimcalpe/router

A simple Router and Dispatcher

  Sources   Download

MIT

The Requires

 

The Development Requires

by Quim Calpe

route

18/11 2015

0.3.0

0.3.0.0 https://github.com/quimcalpe/router

A simple Router and Dispatcher

  Sources   Download

MIT

The Requires

 

The Development Requires

by Quim Calpe

route

11/11 2015

0.2.5

0.2.5.0 https://github.com/quimcalpe/router

A simple Router and Dispatcher

  Sources   Download

MIT

The Requires

 

The Development Requires

by Quim Calpe

route

27/10 2015

0.2.4

0.2.4.0 https://github.com/quimcalpe/router

A simple Router and Dispatcher

  Sources   Download

MIT

The Requires

 

The Development Requires

by Quim Calpe

route

20/07 2015

0.2.3

0.2.3.0 https://github.com/quimcalpe/router

A simple Router and Dispatcher

  Sources   Download

MIT

The Requires

 

The Development Requires

by Quim Calpe

route

05/06 2015

0.2.1

0.2.1.0 https://github.com/quimcalpe/router

A simple Router and Dispatcher

  Sources   Download

MIT

The Requires

 

The Development Requires

by Quim Calpe

route

05/06 2015

0.2.2

0.2.2.0 https://github.com/quimcalpe/router

A simple Router and Dispatcher

  Sources   Download

MIT

The Requires

 

The Development Requires

by Quim Calpe

route

28/05 2015

0.2.0

0.2.0.0 https://github.com/quimcalpe/router

A simple Router and Dispatcher

  Sources   Download

MIT

The Requires

 

The Development Requires

by Quim Calpe

route

22/05 2015

0.1.2

0.1.2.0 https://github.com/quimcalpe/router

A simple Router and Dispatcher

  Sources   Download

MIT

The Requires

 

The Development Requires

by Quim Calpe

route

22/05 2015

0.1.1

0.1.1.0 https://github.com/quimcalpe/router

A simple Router and Dispatcher

  Sources   Download

MIT

The Requires

 

The Development Requires

by Quim Calpe

route

22/05 2015

0.1.0

0.1.0.0 https://github.com/quimcalpe/router

A simple Router and Dispatcher

  Sources   Download

MIT

The Requires

 

The Development Requires

by Quim Calpe

route