简体   繁体   English

引用定义为多维数组的PHP-DI定义

[英]Referencing PHP-DI definitions defined as multi-dimensional arrays

If I have an array of definitions like below, the injection of a RouteCollector instance in other objects is executed perfectly: 如果我有如下所示的定义数组,则可以完美地执行在其他对象中注入RouteCollector实例:

use MyApp\Routing\RouteCollector;

return [
    'router.options.routeParser' => 'FastRoute\\RouteParser\\Std',
    'router.options.dataGenerator' => 'FastRoute\\DataGenerator\\GroupCountBased',
    RouteCollector::class => DI\object()
            ->constructorParameter('routeParser', DI\get('router.options.routeParser'))
            ->constructorParameter('dataGenerator', DI\get('router.options.dataGenerator')),
];

But is there a way to achieve the same result if I define the router.options definition as array? 但是,如果将router.options定义定义为数组,是否有办法实现相同的结果? Eg how can I reference its elements in the RouteCollector::class definition? 例如,如何在RouteCollector::class定义中引用其元素?

use MyApp\Routing\RouteCollector;

return [
    'router.options' => [
        'routeParser' => 'FastRoute\\RouteParser\\Std',
        'dataGenerator' => 'FastRoute\\DataGenerator\\GroupCountBased',
    ],
    RouteCollector::class => DI\object()
            ->constructorParameter('routeParser', <ASKING>)
            ->constructorParameter('dataGenerator', <ASKING>),
];

Please note that it is not about passing the corresponding fully qualified class name (like \\FastRoute\\RouteParser\\Std ) as argument to the constructorParameter method. 请注意,这并不是\\FastRoute\\RouteParser\\Std相应的完全限定的类名(例如\\FastRoute\\RouteParser\\Std )作为参数传递给constructorParameter方法。 It's about referencing a config option defined in an array, in general. 通常,它是关于引用数组中定义的config选项。

Thank you for your support. 谢谢您的支持。

This is not possible out of the box. 这是不可能的。 You could however do something like this (but it's not very readable): 但是,您可以执行以下操作(但它不太可读):

RouteCollector::class => DI\object()
        ->constructorParameter('routeParser', DI\factory(function ($c) {
              return $c->get('router.options')['routeParser'];
          }))

With the future v6.0 you will also be able to remove the DI\\factory and directly put the closure. 在未来的v6.0中,您还可以删除DI\\factory并直接放入封盖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM