-
Notifications
You must be signed in to change notification settings - Fork 0
Bootmanager
Sometimes you might find it necessary to store urls in a database, file or similar. In this example, we want the url /router/article/view/1/
to load the route /router/hello-world/
which the router knows, because it's defined in the routing file (i.e. routes.php). Please note the that /router
part of the url is an example of when the route is installed in a subdirectory. For this example, the route is installed in a subdirectory named router
.
To interfere with the router, we create a class that implements the Qubus\Routing\Interfaces\BootManager
interface. This class will be loaded before any other rules in routes.php and allow us to "change" the current route, if any of our criteria are fulfilled (like coming from the url /router/article/view/1/
).
<?php
namespace Mvc\App\Rules;
use Psr\Http\Message\RequestInterface;
use Qubus\Routing\Interfaces\BootManager;
use Qubus\Routing\Router;
class CustomRouterRules implements BootManager
{
/**
* Called when router is booting and before the routes are loaded.
*
* @param \Qubus\Routing\Router $router
* @param \Psr\Http\Message\RequestInterface $request
*/
public function boot(Router $router, RequestInterface $request): void
{
$rewriteRules = [
'/router/article/view/1/' => '/router/hello-world/'
];
foreach ($rewriteRules as $url => $rule) {
/**
* If the current url matches the rewrite url, we use our custom route.
*/
if ($request->getUrl()->getPath() === $url) {
$request->setRewriteUrl($rule);
}
}
}
}
The last thing we need to do, is to add our custom boot-manager to the routes.php
file. You can create as many bootmanagers as you like and easily add them in your routes.php
file.
$router->addBootManager(new \Mvc\App\Rules\CustomRouterRules());