PHP-Router icon indicating copy to clipboard operation
PHP-Router copied to clipboard

Attach routes to basePath

Open antoine-pous opened this issue 8 years ago • 0 comments

I think it would be cool to attach routes to basePath like that:

$latestApiVersion = 3;
$collection = new RouteCollection();

// Out of basePath callback, implicit '/'
$collection->attachRoute(new Route('/home', array(
    '_controller' => 'webController::home',
    'methods' => 'GET'
)));

// Set the basePath, each route into the callback begin with /api/v2
$collection->basePath('/api/v2', function() {
    $this->attachRoute(new Route('/users', array(
        '_controller' => 'apiController::userlist',
        'methods' => 'GET'
    )));
});

// Advanced basePath
$collection->basePath('/api/v:version', function($version) use($latestApiVersion) {
    
    if((int) $version !== $latestApiVersion) {
        require_once __DIR__ . '/../routes/api.deprecated.php';
    } else {
        $this->attachRoute(new Route('/users', array(
            '_controller' => 'apiController::userlist',
            'methods' => 'GET'
        )));
    }
})->setFilters(['version' => '([\d]+)']);

$router = new Router($collection);
$route = $router->matchCurrentRequest();

var_dump($route);

With this kind of feature we can manage easily many basePath without repeat it in each routes.

antoine-pous avatar Mar 15 '17 12:03 antoine-pous