Skip to content

Dependency Injection Container

Joshua Parker edited this page Dec 23, 2020 · 2 revisions

The router can also be used with a PSR-11 compatible Container of your choosing (PHP-DI is highly recommended). This allows you to type hint dependencies in your route closures or Controller methods.

To make use of a container, simply pass it as a parameter to the Router's constructor:

use DI\Container;
use Qubus\Routing\Route\RouteCollector;
use Qubus\Routing\Router;

$container = new Container();
$router = new Router(new RouteCollector, $container);

After which, your route closures and Controller methods will be automatically type hinted:

$container = new Container();

$testServiceInstance = new TestService();
$container->set(TestService::class, $testServiceInstance);

$router = new Router(new RouteCollector, $container);

$router->get('/my/route', function (TestService $service) {
    // $service is now the same object as $testServiceInstance
});
Clone this wiki locally