dongliang2058 2015-07-21 19:09
浏览 34
已采纳

用于ctor注入的PHP-DI注册实例

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.

  • 写回答

1条回答 默认 最新

  • dongyijing2353 2015-07-22 08:19
    关注

    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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?