Introducing Stack Based Routing

One of the major benefits of going framework-free in PHP is that you get to produce more modular, composable applications. Stack php is the first building block in this approach and this post shows how you can now let a Stack app handle your application routing.

At its core, the philosophy of the HttpKernelInterface is simple, an http request is analysed, processed and the application returns an http response that is rendered. The main complexity here comes in deciding which controller is able to handle the request and delegating to it.

In a traditional full-stack framework this would have been handled for you, /account/edit would probably map to AccountController::edit or something similar. Of course whilst the magic routing might seem easy to start with you often end up paying for simplicity further down the line.

So, using a standalone router is a much more flexible way to manage your configuration, with a change in configuration /account/edit can point to Namespace\Controller\Account::edit or NewNamespace\Controller\UpdatedAccount::edit.

To keep the Request / Response paradigm throughout the application ecosystem, we can just enhace our Request object with some routing metadata. Thanks to the power of Stack apps this can be done by pushing a RequestRouter on top of the stack.

Implementation

Get the package installed, if you are already using a Stack Builder to power your app, you only need to do the following.

In your composer.json file add this line to your require block

"rossriley/stack-aura-router": "1.0.*@dev"

Then to bootstrap your app, try something like the following.

$router = include(__DIR__."/../config/routes.php");

$app = new YourNamespace\Application;

$app = (new Stack\Builder())
        ->push('Stack\Aura\RequestRouter', $router)
        ->resolve($app);

Stack\run($app);

You can see more detailed documentation on the Github project page, where feature and bug requests are also welcome.