Skip to content
Pedro Faria edited this page Apr 14, 2017 · 2 revisions

Routes

Setup

All routes are defined with the method setRoute. You can pass a closure (above).

$app->setRoute(function(Hope\Router\RouteCollector $route) {
    $route->add('GET', '/ping', function() {
        return ['data' => 'pong'];
    });
});

Or a file name with the route definition.

$app->setRoute(__DIR__ . '/../app/routes.php');

And at app/routes.php file.

<?php

$route->add('GET', '/ping', function() {
    return ['data' => 'pong'];
});

Mapping

Map all your routes to your actions.

$route->add(METHOD, URI, ACTION, [MIDDLEWARE]);

If you want to map more than one method to the same action, use:

$route->add([METHOD1, METHOD2], URI, ACTION, [MIDDLEWARE]);

You can define parameters on URI using braces. Example:

/recipes/{id}

Now the parameter id will be passed to your controller action. You can also specify an regular expression to your parameter to have a better controls of your URIs, example:

/recipes/{id:\d+}

Your actions should be defined as string, array or closures. example:

$route->add('GET', '/recipes', 'App\Controller\RecipesController::index');
$route->add('GET', '/recipes', ['App\Controller\RecipesController', 'index']);
$route->add('GET', '/ping', function () {
	return 'pong';
};

If you have a registered middleware, you can define to use it at the 4th parameter.

$route->add('GET', '/profile', 'App\Controller\ProfileController::viewProfile', ['auth']);

For more information about Middlewares at Hope, check the Middleware documentation.

Additionally, you can specify routes inside of a group. All routes defined inside a group will have a common prefix.

For example, defining your routes as:

$route->addGroup('/admin', function (Hope\Router\RouteCollector $route) {
    $route->add('GET', '/do-something', 'handler');
    $route->add('GET', '/do-another-thing', 'handler');
    $route->add('GET', '/do-something-else', 'handler');
}, ['logger']);

Will have the same result as:

$route->add('GET', '/admin/do-something', 'handler', ['logger']);
$route->add('GET', '/admin/do-another-thing', 'handler', ['logger']);
$route->add('GET', '/admin/do-something-else', 'handler', ['logger']);

Nested groups are also supported, in which case the prefixes of all the nested groups are combined.

For more informations, access https://github.com/pedrofaria/router

Clone this wiki locally