DotKernel 3 uses FastRoute under the hood, which is an excellent and fast routing package, but it does have some quirks.

A wrong setup can lead to many headaches, as it’s not prominent that the error you’re experiencing is from FastRoute, and you may not know where exactly to look for the cause.

To save you some time, here’s a how-to for creating and using routes in DotKernel 3.


Declaring routes

When defining routes in the routes.php file, they need to follow a specific pattern, a usual route would look like this:

$app->route('/page[/{action}]', [PageController::class], ['GET', 'POST'], 'page');

Notice the /page[/{action}] part, as this is crucial. FastRoute cannot handle a slash-suffix, which means that /page will give you the indexAction, whereas /page/ will give you a 404.

To prevent the URLGenerator from adding a slash-suffix, we need to make sure that the optional slash is included in the optional block. The above example is correct, if we instead wrote it like this, it’d be woefully bad.

$app->route('/page/[{action}]', [PageController::class], ['GET', 'POST'], 'page');

Notice that the slash has changed places and is now outside the optional block. This would generate a /page/ route for the index action, which is bad, so always include any optional parts, even slashes, in the optional block.


Referencing routes

Developers are used to hand-write and hard-code URLs into anchor tags, but this is a bad idea, as a URL may change and then you’d have to go through the entire app to find every single reference for it. Instead, every route we define has a name that can be used to reference it in the URLGenerator.

$app->route('/page[/{action}]', [PageController::class], ['GET', 'POST'], 'page');

That very last part there, that’s the route name, which can be referenced in any view or controller to generate a route to a specific route in the app.

To use it in a Controller, you have access to $this->url(); which takes the route name, in this case, ‘page‘, as the first parameter, and then any optional blocks as the second parameter.

A controller redirect may then look like this:

return new RedirectResponse($this->url('contact', ['action' => 'thank-you']));

Using the URLGenerator in views is approximately the same, since you have access to the global path() method.

The path method works the same way as the url() method, and takes the route name as the first parameter, and any optional blocks as its second parameter. This is of course done in Twig, so we need to put curly brackets around it since it’s dynamic and not static HTML. It could look like this:

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>