Search code examples
ioc-containerslim-3thephpleague

Slim 3 + Pleague 2.4 - Alias (router) is not being managed by the container?


How do I use Pleaguev2.4 with Slim v3.8.1?

Following this example, I tried:

// PSR 7 standard.
use Slim\Http\Request;
use Slim\Http\Response;

// Import classes.
use Slim\App as Slim;

use League\Container\Container;
$container = new Container;

// Required to enable auto wiring.
$container->delegate(
    new \League\Container\ReflectionContainer
);

// Get an instance of Slim.
$app = new Slim($container);

I get:

Fatal error: Uncaught League\Container\Exception\NotFoundException: Alias (router) is not being managed by the container in /var/www/html/projectA/vendor/league/container/src/Container.php:266 Stack trace: #0 /var/www/html/projectA/vendor/league/container/src/Container.php(93): League\Container\Container->getFromDelegate('router', Array) #1 /var/www/html/projectA/vendor/slim/slim/Slim/App.php(239): League\Container\Container->get('router') #2 /var/www/html/projectA/vendor/slim/slim/Slim/App.php(143): Slim\App->map(Array, '/', Object(Closure)) #3 /var/www/html/projectA/public/index.php(53): Slim\App->get('/', Object(Closure)) #4 {main} thrown in /var/www/html/projectA/vendor/league/container/src/Container.php on line 266

Any ideas?


Solution

  • Slim is trying to access the router which isn't defined on the container you've added. In Slim they will be added by the \Slim\DefaultServicesProvider. But you cannot use it because your DI Container doesn't support array access.

    An option to fix this problem is to set the Slim container as delegate, then the League\Container\Container will get the router and all other stuff through the slim container:

    $container = new \League\Container\Container;
    $container->delegate(new \Slim\Container());
    $app = new \Slim\App($container);