Introduction
This section gives you a nice rundown of the router. Any place in the application where Qubus\Routing\Router or
Qubus\Routing\Psr7Router is the dependency, the Container will resolve the dependency.
Basic Routing
Below is a basic example of setting up a route. The route's first parameter is the uri, and the second parameter is a closure or callback.
<?php
declare(strict_types=1);
use Application\Http\Controller\HomeController;
return (function(\Qubus\Routing\Psr7Router $router) {
$router->get('/', function(HomeController $controller) {
return $controller->index();
});
});
File: ./routes/web/web.php
File Routing
File based routing is the default way in which routes are loaded:
<?php
declare(strict_types=1);
use Application\Http\Controller\HomeController;
use Application\Http\Middleware\AddHeaderMiddleware;
return function (\Qubus\Routing\Psr7Router $router) {
$router->get('/', function(HomeController $controller) {
return $controller->index();
})
->middleware(AddHeaderMiddleware::class);
};
File: ./routes/web/web.php
Then you can add the route file(s) to the withRouting method of the application:
<?php
declare(strict_types=1);
use Codefy\Framework\Application as DevflowApp;
use Qubus\Exception\Data\TypeException;
use function Codefy\Framework\Helpers\env;
try {
$app = DevflowApp::create(
config: [
'basePath' => env(key: 'APP_BASE_PATH', default: dirname(path: __DIR__))
]
)
//->withEncryptedEnv(bool: true)
->withProviders([
//
])
->withSingletons([
//
])
->withRouting(
web: [
dirname(path: __DIR__) . '/routes/web/admin.php',
dirname(path: __DIR__) . '/routes/api/v1.php',
dirname(path: __DIR__) . '/routes/api/v2.php',
dirname(path: __DIR__) . '/routes/web/web.php',
],
)
->return();
$app->share(nameOrInstance: $app);
return $app::getInstance();
} catch (TypeException|ReflectionException $e) {
return $e->getMessage();
}
File: ./bootstrap/app.php
Class Routing
One last method you can use to add routes is by creating route classes:
<?php
declare(strict_types=1);
namespace Application\Http\Route;
use Application\Http\Controller\HomeController;
use Application\Http\Middleware\AddHeaderMiddleware;
use Qubus\Routing\Psr7Router;
readonly class WebRoute
{
public function __construct(public Psr7Router $router)
{
}
public function handle(): void
{
$this->router->get('/', function(HomeController $controller) {
return $controller->index();
})
->middleware(AddHeaderMiddleware::class);
}
}
File: ./Cms/Application/Http/Route/WebRoute.php
Or you can bypass adding a constructor and instead add the Router dependency to the handle method:
<?php
declare(strict_types=1);
namespace Application\Http\Route;
use Application\Http\Controller\HomeController;
use Application\Http\Middleware\AddHeaderMiddleware;
use Qubus\Routing\Psr7Router;
readonly class WebRoute
{
public function handle(Psr7Router $router): void
{
$this->router->get('/', function(HomeController $controller) {
return $controller->index();
})
->middleware(AddHeaderMiddleware::class);
}
}
File: ./Cms/Application/Http/Route/WebRoute.php
Then you can add the route class to the withRouting method of the application:
<?php
declare(strict_types=1);
use Application\Http\Route\WebRoute;
use Codefy\Framework\Application as DevflowApp;
use Qubus\Exception\Data\TypeException;
use function Codefy\Framework\Helpers\env;
try {
$app = DevflowApp::create(
config: [
'basePath' => env(key: 'APP_BASE_PATH', default: dirname(path: __DIR__))
]
)
->withProviders([
//
])
->withSingletons([
//
])
->withRouting(
class: [
WebRoute::class,
],
)->return();
$app->share(nameOrInstance: $app);
return $app::getInstance();
} catch (TypeException $e) {
return $e->getMessage();
}
File: ./bootstrap/app.php
Http Methods
Sometimes you might need to create a route that accepts multiple HTTP verbs. For this you can use the map method.
However, If you need to match all HTTP verbs, you can use the any method.
<?php
declare(strict_types=1);
return function (\Qubus\Routing\Psr7Router $router) {
$router->map(['GET', 'POST'], '/', function() {
// ...
});
$router->any('test', function() {
// ...
});
};
File: ./routes/web/web.php
Http Verb Shortcuts
In most typical cases, you will only need to use one HTTP verb. The following can be used in those cases:
<?php
declare(strict_types=1);
return function (\Qubus\Routing\Psr7Router $router) {
$router->get('test/route', function () {});
$router->head('test/route', function () {});
$router->post('test/route', function () {});
$router->put('test/route', function () {});
$router->patch('test/route', function () {});
$router->delete('test/route', function () {});
$router->options('test/route', function () {});
$router->trace('test/route', function () {});
$router->connect('test/route', function () {});
$router->any('test/route', function () {});
};
File: ./routes/web/web.php
Route Parameters
Parameters can be defined on routes using the {keyName} syntax. When a route matches a contained parameter,
an instance of the RouteParams object is passed to the action.
<?php
declare(strict_types=1);
return function (\Qubus\Routing\Psr7Router $router) {
$router->map(['GET'], 'posts/{id}', function($id) {
return $id;
});
};
File: ./routes/web/web.php
If you need to add constraints to a parameter, you can pass a regular expression pattern to the where() method of the
defined Route:
<?php
declare(strict_types=1);
return function (\Qubus\Routing\Psr7Router $router) {
// the regex for 'id' is for ULID's
$router->map(['GET'], 'post/{id}/comment/{commentKey}', function ($id, $commentKey) {
return $id;
})
->where(['id', '[0123456789ABCDEFGHJKMNPQRSTVWXYZ{26}$]+'])
->where(['commentKey', '[a-zA-Z]+']);
};
File: ./routes/web/web.php
Optional Route Parameters
Sometimes you may want to use optional route parameters. To achieve this, you can add a ? after the parameter name:
<?php
declare(strict_types=1);
return function (\Qubus\Routing\Psr7Router $router) {
$router->map(['GET'], 'posts/{id?}', function($id) {
if (isset($id)) {
// Parameter is set.
} else {
// Parameter is not set.
}
});
};
File: ./routes/web/web.php
Named Routes
Routes can be named so that their URL can be generated programmatically:
<?php
declare(strict_types=1);
return function (\Qubus\Routing\Psr7Router $router) {
$router->map(['GET'], 'post/all', function () {})->name('posts.index');
};
File: ./routes/web/web.php
<?php
declare(strict_types=1);
namespace Application\Http\Controller;
use Psr\Http\Message\ResponseInterface;
use Qubus\Routing\Psr7Router;
use function Codefy\Framework\Helpers\trans;
use function Codefy\Framework\Helpers\view;
final class PostController
{
public function __construct(protected Psr7Router $router)
{
}
public function index(): ResponseInterface
{
return view(
template: 'cmf::post/index',
data: [
'title' => trans('Posts'),
'url' => $this->router->url(name: 'posts.index'),
]
);
}
```
}
File: ./Cms/Application/Http/Controller/PostController.php
If the route requires parameters, you can pass an associative array as a second parameter:
<?php
declare(strict_types=1);
return function (\Qubus\Routing\Psr7Router $router) {
$router->map(['GET'], 'post/{id}', function () {})->name('posts.show');
};
File: ./routes/web/web.php
<?php
declare(strict_types=1);
namespace Application\Http\Controller;
use Codefy\Framework\Http\BaseController;
use Psr\Http\Message\ResponseInterface;
use Qubus\Routing\Psr7Router;
use function Codefy\Framework\Helpers\trans;
use function Codefy\Framework\Helpers\view;
final class PostController
{
public function __construct(protected Psr7Router $router)
{
}
public function show(string $id): ResponseInterface
{
return view(
template: 'cmf::post/index',
data: [
'title' => trans('Posts'),
'url' => $this->router->url(name: 'posts.show', ['id' => $id]),
]
);
}
```
}
File: ./Cms/Application/Http/Controller/PostController.php
If a parameter fails the regex constraint applied, a RouteParamFailedConstraintException will be thrown.
Route Groups
It is common to group similar routes behind a common prefix. This can be achieved using RouteGroup:
<?php
declare(strict_types=1);
return function (\Qubus\Routing\Psr7Router $router) {
$router->group(['prefix' => 'page'], function (\Qubus\Routing\Route\RouteGroup $group) {
$group->map(['GET'], '/route1/', function () {}); // `/page/route1/`
$group->map(['GET'], '/route2/', function () {}); // `/page/route2/`
});
};
File: ./routes/web/web.php
Route Prefixes
The prefix group attribute may be used to prefix each route in the group with a given url. For example, you may want to
prefix all route urls within the group with admin:
<?php
declare(strict_types=1);
return function (\Qubus\Routing\Psr7Router $router) {
$router->group(['prefix' => 'admin'], function (\Qubus\Routing\Route\RouteGroup $group) {
$group->get('/users/', function () {
// Matches The "/admin/users/" URL
});
});
};
File: ./routes/web/web.php
Routing Middleware
PSR-7/15 Middleware can be added to both routes and groups.
Adding Middleware to a route
At it's simplest, adding Middleware to a route can be done by passing an object to the middleware() method:
<?php
declare(strict_types=1);
use Application\Http\Controller\HelloWorldController;
return function (\Qubus\Routing\Psr7Router $router) {
$middleware = new \Application\Http\Middleware\AddHeaderMiddleware('X-Key1', 'abc');
$router->get('hello-world', function(HelloWorldController $controller) {
return $controller->sayHello();
})
->middleware($middleware);
};
File: ./routes/web/web.php
Multiple middleware can be added by passing more parameters to the middleware() method:
<?php
declare(strict_types=1);
use Application\Http\Controller\TestController;
return function (\Qubus\Routing\Psr7Router $router) {
$header = new \Application\Http\Middleware\AddHeaderMiddleware('X-Key1', 'abc');
$auth = new \Application\Http\Middleware\AuthMiddleware();
$router->get('auth', function(TestController $controller) {
return $controller->testMethod();
})
->middleware($header, $auth);
};
File: ./routes/web/web.php
Or alternatively, you can also pass an array of middleware:
<?php
declare(strict_types=1);
use Application\Http\Controller\TestController;
return function (\Qubus\Routing\Psr7Router $router) {
$header = new \Application\Http\Middleware\AddHeaderMiddleware('X-Key1', 'abc');
$auth = new \Application\Http\Middleware\AuthMiddleware();
$router->get('auth', function(TestController $controller) {
return $controller->testMethod();
})
->middleware([$header, $auth]);
};
File: ./routes/web/web.php
Adding Middleware to all routes
If you would like to add a middleware that is going to affect all routes, then use the setBaseMiddleware method.
<?php
declare(strict_types=1);
return function (\Qubus\Routing\Psr7Router $router) {
$router->setBaseMiddleware([
new \Application\Http\Middleware\AddHeaderMiddleware('X-Key', 'abc'),
]);
};
File: ./routes/web/web.php
Since all your routes may not be in one file, the alternative and recommended way of setting base middlewares is by setting them in the app config:
<?php
//....
/*
|--------------------------------------------------------------------------
| Base Middlewares
|--------------------------------------------------------------------------
| Register middleware class strings or aliases to be applied to the entire
| application.
*/
'base_middlewares' => [
'csrf.token',
'csrf.protection',
'http.cache.prevention',
],
//....
File: ./config/app.php
Adding Middleware to a group
Middleware can also be added to a group. To do so you need to pass an array as the first parameter of the group()
function instead of a string.
<?php
declare(strict_types=1);
return function (\Qubus\Routing\Psr7Router $router) {
$header = new \Application\Http\Middleware\AddHeaderMiddleware('X-Key1', 'abc');
$router->group(['prefix' => 'my-prefix', 'middleware' => $header]), function (\Qubus\Routing\Route\RouteGroup $group) {
$group->map(['GET'], 'route1', function () {}); // `/my-prefix/route1`
$group->map(['GET'], 'route2', function () {}); // `/my-prefix/route2`
});
};
File: ./routes/web/web.php
You can also pass an array of middleware if you need more than one:
<?php
declare(strict_types=1);
return function (\Qubus\Routing\Psr7Router $router) {
$header = new \Application\Http\Middleware\AddHeaderMiddleware('X-Key1', 'abc');
$auth = new \Application\Http\Middleware\AuthMiddleware();
$router->group(['prefix' => 'my-prefix', 'middleware' => [$header, $auth]]), function (\Qubus\Routing\Route\RouteGroup $group) {
$group->map(['GET'], 'route1', function () {}); // `/my-prefix/route1`
$group->map(['GET'], 'route2', function () {}); // `/my-prefix/route2`
});
};
File: ./routes/web/web.php
Events
This section will help you understand how to register your own callbacks to events in the router. It will also cover the basics of event-handlers; how to use the handlers provided with the router and how to create your own custom event-handlers.
Available Events
This section contains all available events that can be registered using the RoutingEventHandler.
All event callbacks will retrieve a RoutingEventArgument object as parameter. This object contains easy access to
event-name, router- and request instance and any special event-arguments related to the given event. You can see what
special event arguments each event returns in the list below.
| Name | Special arguments | Description |
|---|---|---|
EVENT_ALL |
- | Fires when a event is triggered. |
EVENT_INIT |
- | Fires when router is initializing and before routes are loaded. |
EVENT_LOAD |
loadedRoutes |
Fires when all routes have been loaded and rendered, just before the output is returned. |
EVENT_ADD_ROUTE |
route |
Fires when route is added to the router. |
EVENT_BOOT |
bootmanagers |
Fires when the router is booting. This happens just before boot-managers are rendered and before any routes has been loaded. |
EVENT_RENDER_BOOTMANAGER |
bootmanagersbootmanager |
Fires before a boot-manager is rendered. |
EVENT_LOAD_ROUTES |
routes |
Fires when the router is about to load all routes. |
EVENT_FIND_ROUTE |
name |
Fires whenever the has method is used. |
EVENT_GET_URL |
nameparams |
Fires whenever the Router::url method is called and the router tries to find the route. |
EVENT_MATCH_ROUTE |
route |
Fires when a route is matched and valid (correct request-type etc). and before the route is rendered. |
EVENT_RENDER_MIDDLEWARES |
routemiddlewares |
Fires before middlewares for a route is rendered. |
To register a new event you need to create a new instance of Qubus\Routing\Events\RoutingEventHandler object. You can
add as many callbacks as you like by calling the registerEvent method.
When you've registered events, make sure to add it to your routes file by calling the addEventHandler method from the
router. It's recommend that you add your event-handlers within routes/web/web.php.
<?php
declare(strict_types=1);
use Qubus\Routing\Events\RoutingEventHandler;
use Qubus\Routing\Events\RoutingEventArgument;
return (function(\Qubus\Routing\Psr7Router $router) {
// --- your routes go here ---
$eventHandler = new RoutingEventHandler();
// Add event that fires when a route is rendered
$eventHandler->register(RoutingEventHandler::EVENT_ADD_ROUTE, function(RoutingEventArgument $argument) {
// Get the route by using the special argument for this event.
$route = $argument->route;
// DO STUFF...
});
$router->addEventHandler($eventHandler);
});
File: ./routes/web/web.php
Custom EventHandlers
Qubus\Routing\Events\RoutingEventHandler is the class that manages events and must inherit from the
Qubus\Routing\Events\EventHandler contract. The handler knows how to handle events for the given handler type.
Most of the time the basic Qubus\Routing\Events\RoutingEventHandler class will be more than enough for most people as
you simply register an event which fires when triggered.
Let's go over how to create your very own event handler class.
Below is a basic example of a custom event-handler called DatabaseDebugHandler. The idea of the example below is to
log all events to the database when triggered. Hopefully this is enough to give you an idea of how event handlers work.
<?php
declare(strict_types=1);
namespace Infrastructure\Service;
use Qubus\Routing\Events\EventHandler;
use Qubus\Routing\Events\RoutingEventArgument;
use Qubus\Routing\Psr7Router;
class DatabaseDebugHandler implements EventHandler
{
/**
* Debug callback
* @var \Closure
*/
protected $callback;
public function __construct()
{
$this->callback = function (RoutingEventArgument $argument) {
// todo: store log in database
};
}
/**
* Get events.
*
* @param string|null $name Filter events by name.
* @return array
*/
public function getEvents(?string $name): array
{
return [
$name => [
$this->callback,
],
];
}
/**
* Fires any events registered with given event name
*
* @param Router $router Router instance
* @param string $name Event name
* @param array ...$eventArgs Event arguments
*/
public function fireEvents(Psr7Router $router, string $name, ...$eventArgs): void
{
$callback = $this->callback;
$callback(new RoutingEventArgument($router, $eventArgs));
}
/**
* Set debug callback
*
* @param \Closure $event
*/
public function setCallback(\Closure $event): void
{
$this->callback = $event;
}
}
File: ./Cms/Infrastructure/Service/DatabaseDebugHandler.php
BootManager with URL Rewriting
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/web/web.php). Please note that the /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/web/web.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
declare(strict_types=1);
namespace Infrastructure\Service;
use Psr\Http\Message\RequestInterface;
use Qubus\Routing\Interfaces\BootManager;
use Qubus\Routing\Psr7Router;
class CustomRouterRules implements BootManager
{
/**
* Called when router is booting and before the routes are loaded.
*
* @param \Qubus\Routing\Psr7Router $router
* @param \Psr\Http\Message\RequestInterface $request
*/
public function boot(Psr7Router $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);
}
}
}
}
File: ./Cms/Infrastructure/Service/CustomRouterRules.php
The last thing you need to do, is to add your custom boot-manager to the routes/web/web.php file. You can create as
many bootmanagers as you like and easily add them in your routes/web/web.php file.
<?php
declare(strict_types=1);
use Qubus\Routing\Events\RoutingEventHandler;
use Qubus\Routing\Events\RoutingEventArgument;
return (function(\Qubus\Routing\Psr7Router $router) {
// --- your routes go here ---
$router->addBootManager(new \App\Infrastructure\Services\CustomRouterRules());
});
File: ./routes/web/web.php
Misc.
If you return an instance of Response from your closure it will be sent back un-touched. If however you return
something else, it will be wrapped in an instance of Response with your return value as the content.
Responsable objects
If you return an object from your closure that implements the Responsable interface, it's toResponse() object will
be automatically called for you.
<?php
declare(strict_types=1);
namespace Infrastructure\Service;
use Laminas\Diactoros\Response\TextResponse;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Qubus\Routing\Interfaces\Responsable;
class HelloWorldObject implements Responsable
{
public function toResponse(RequestInterface $request): ResponseInterface
{
return new TextResponse('Hello World!');
}
}
File: ./src/Infrastructure/Service/HelloWorldObject.php
<?php
declare(strict_types=1);
return (function(\Qubus\Routing\Psr7Router $router) {
$router->get('hello-world', function () {
return new HelloWorldObject();
});
});
File: ./routes/web/web.php
404
If no route matches the request, a Response object will be returned with its status code set to 404;
Accessing Current Route
The currently matched Route can be retrieved by calling:
If no route matches or match() has not been called, null will be returned.
You can also access the name of the currently matched Route by calling:
If no route matches or match() has not been called or the matched route has no name, null will be returned.