Routing is done by adding a set of routes to the application with the addRoute method.
Each route matches the request path in the url with a specified controller class. If a route matches the request path, the controller is created and a suitable action method is invoked.
Routes are evaluated in the order they were added. If a match was found, no more routes are evaluated.
If no matching route was found, a 404 Not Found response is returned.
To add a standard route, use the BlueMvc\Core\Route class.
A Route is constructed with two parameters:
The path matched is the directory part of the url. Leading and trailing directory separators (/) are implied.
Example 1: Matches / or /foo or /bar and so on, but not /foo/ or /foo/bar
new Route('', MyController::class)
Example 2: Matches /foo/ or /foo/bar or /foo/bar/ and so on, but not /foo
new Route('foo', MyController::class)
Example 3: Matches /foo/bar/ or /foo/bar/baz or /foo/bar/baz/ and so on, but not /foo/bar
new Route('foo/bar', MyController::class)
A default route serves as a "catch-all" route and should therefore, if used, be added last.
To add a default route, use the BlueMvc\Core\DefaultRoute class.
A DefaultRoute is constructed by passing the controller class name in the constructor.
Consider the following example setup:
$application->addRoute(new Route('', IndexController::class)); $application->addRoute(new Route('a/b', AliceBobController::class)); $application->addRoute(new Route('a', AliceController::class)); $application->addRoute(new Route('a/c', AliceCharlieController::class)); $application->addRoute(new DefaultRoute(DefaultController::class));
Using the setup above, these examples illustrates which controller will be used for different requests.
|Request path||Controller used|
Note that AliceController was used instead of AliceCharlieController for the request path /a/c/. In fact, the AliceCharlieController will never be used in this setup, since all paths that matches 'a/c' also matches 'a', which was added first. The same reasoning applies to /a/c/x.
✎ Published in category core