Search code examples
phpdependency-injectionphp-di

PHP-DI Register Instance for ctor Injection


I'm using php-di and am using twig in my project. I'd like to register the instance of $twig with php-di so that its instance is injected into the ctor argument on objects where it's needed. I'd like to use php definitions and avoid phpdoc annotations, and have read this http://php-di.org/doc/php-definitions.html

Here's my basic example:

$builder = new ContainerBuilder();
$builder->addDefinitions(['Twig_Environment' => $twig]);
$container = $builder->buildDevContainer();

Then I have $twig as a ctor argument in some other classes. Is this even possible? To be clear, I don't want to have to create a definition for each object that uses $twig.

public function __construct(\Twig_Environment $twig)
{
    $twig->render('homepage.twig');
}

The error I'm getting indicates that php-di is trying to create a new instance of Twig_Environment instead of using the instance already created.


Solution

  • This is all correct, except for the method you call to create the container:

    $container = $builder->buildDevContainer();
    

    That creates an entirely new container and ignores what you have configured above ;) (it's actually a static method that you can use to create a new container very easily like this: $container = ContainerBuilder::buildDevContainer();).

    You should use instead:

    $container = $builder->build();