obullo/router

Php7 standalone router inspired by the Django Url Dispatcher. Easy to use and Secure.

1.0.4 2018-04-24 18:01 UTC

README

Build Status Software License Total Downloads

Obullo router is a standalone route package inspired by the Django Url Dispatcher.

Install

$ composer require obullo/router

Requirements

The following versions of PHP are supported by this version.

  • 7.0
  • 7.1
  • 7.2

Testing

$ vendor/bin/phpunit

Quick start

require '../vendor/autoload.php';

use Obullo\Router\Route;
use Obullo\Router\RequestContext;
use Obullo\Router\RouteCollection;
use Obullo\Router\Router;
use Obullo\Router\Types\{
    StrType,
    IntType
};
$config = array(
    'types' => [
        new IntType('<int:id>'),
        new StrType('<str:name>'),
    ]
);

Psr7 Request

$request = Zend\Diactoros\ServerRequestFactory::fromGlobals();
$context = new RequestContext;
$context->fromRequest($request);

Route Collection

$collection = new RouteCollection($config);
$collection->setContext($context);
$collection->add('home', new Route('GET', '/', 'App\Controller\DefaultController::index'));
$collection->add(
    'dummy',
    new Route(
        'GET',
        '/dummy/index/<int:id>/<str:name>',
        'App\Controller\DummyController::index'
        ['App\Middleware\Dummy::class']
    )
);

Route Class

$route = $collection->get('dummy');

echo $route->getHandler(); //  "App\Controller\DummyController::index"
echo $route->getMethods()[0]; // GET
echo $route->getPattern(); //  "/dummy/index/(?\d+)/(?\w+)"
echo $route->getStack()[0]; // App\Middleware\Dummy::class

Dispatching

$router = new Router($collection);

if ($route = $router->matchRequest()) {

    $handler = $route->getHandler();
    $args = array_merge(array('request' => $request), $route->getArguments());
    $response = null;
    if (is_callable($handler)) {
        $exp = explode('::', $handler);
        $class = new $exp[0];
        $method = $exp[1];
        $response = call_user_func_array(array($class, $method), $args);
    }
    if ($response instanceof Psr\Http\Message\ResponseInterface) {
        echo $response->getBody();  // DummyController::index
    }
}

App\Controller\DummyController

namespace App\Controller;

use Zend\Diactoros\Response\HtmlResponse;
use Psr\Http\Message\RequestInterface as Request;

class DummyController
{
    public function index(Request $request)
    {
        return new HtmlResponse('DummyController::index');
    }
}

Documentation

Documents are available at http://router.obullo.com/