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

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法