Inspired from Django Url Dispatcher. Easy to use and Secure.
Switch branches/tags
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
src
tests
website
.gitignore
.travis.yml
CHANGELOG.md
LICENSE.md
README.md
composer.json
phpunit.xml

README.md

Obullo / Router

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/