Router
This library provides a leightweight router based on regular expressions., (*1)
, (*2)
Diclaimer : This component is part of the WOK (Web Operational Kit) framework.
It however can be used as a standalone library., (*3)
Install
It is recommanded to install that component as a dependency using Composer :, (*4)
composer require wok/router
You're also free to get it with git or by direct download while this package has no dependencies., (*5)
git clone https://github.com/web-operational-kit/router.git
Features
As any other router, these features are available :, (*6)
- Routing with a method and a URI (see the usage section)
- Route Parameters replacing and matching
- Manipulating routes definition afterwards
- Retrieving routes meta data independently
- Routes collection manipulation
Note :
Some features will not be implemented for now because of the wish of simplicity (and independance) of that library., (*7)
This is why the dispatcher does not execute any function. It only returns the first matching route with the information that would be needed., (*8)
Make your own opinion :), (*9)
Basic usage
``` php
use \WOK\Router\Route;
use \WOK\Router\Collection;, (*10)
// First instanciate a collection
$collection = new Collection();, (*11)
$collection = new Collection();
$collection->addRoute(
new Route(
['POST', 'GET', 'HEAD'],// Define the accepted HTTP methods
'/path/to/the/{resource}', // Define the route URI
[ // Define the URI parameters
'resource' => '[a-z0-9-]+'
]
),
'Controller::action', // Define the target (function name, class, object, array, Closure, ...)
'Controller->Action' // Define the route name
);, (*12)
// Define many other routes ..., (*13)
// Retrieve the first matching route
try {, (*14)
$route = $collection->match('GET', '/path/to/the/resource-file-name');
}, (*15)
// No route match the current request
catch(\DomainException $e) {, (*16)
$route = (object) array(
'name' => 'Controller->pageNotFound',
'action' => ['Controller', 'pageNotFound'],
'parameters' => []
);
}, (*17)
// Play with the route value
call_user_func_array($route->action, $route->parameters);
```, (*18)
Warning:
To prevent any borring returned value the Collection::match throws a DomainException if no route is found., (*19)
That way, feel free to define any not found behavior, (*20)