0

If I have an array of definitions like below, the injection of a RouteCollector instance in other objects is executed perfectly:

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? E.g. how can I reference its elements in the RouteCollector::class definition?

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. It's about referencing a config option defined in an array, in general.

Thank you for your support.

1 Answers1

0

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.

Matthieu Napoli
  • 48,448
  • 45
  • 173
  • 261
  • Thank you, Matthieu. I thought that it won't work as I presented, but I hoped that I missed a feature doing just that, somewhere in the docs/code of PHP-DI... Indeed, not very readable, but a good suggestion. I know now that it's possible and I will balance the use of it... In other order, I want to congratulate you for the great PHP-DI project! Good luck! –  Jan 11 '18 at 15:10