zendframework / zend-di

Di component from Zend Framework
BSD 3-Clause "New" or "Revised" License
46 stars 29 forks source link

Do not check the type of parameter for string #49

Closed michalbundyra closed 5 years ago

michalbundyra commented 5 years ago

Issue description

Please consider the following configuration:

'service-manager' => [
    'factories' => [
        'my-service.config' => MyServiceConfigFactory::class,
    ],
],
'dependencies' => [
    'auto' => [
        'types' => [
            MyController::class => [
                'parameters' => [
                    'config' => 'my-service.config',
                ],
            ],
        ],
    ],
],

where MyController is as follows:

class MyController
{
    public function __construct(Config $config) {}
}

according to the documentation

An IoC container service name as string: This is only possible if the required type is a class or interface. For other types (scalars, iterable, callable, etc) or typeless parameters, the string value is passed as is. (see: https://docs.zendframework.com/zend-di/config/#parameters)

it should work correctly, so we should have generated factory for MyController:

class MyControllerFactory
{
    public function __invoke(ContainerInterface $container)
    {
        return new MyController($container->get('my-service.config'));
    }
}

but unfortunately parameter resolver try to check the type. If we add:

`dependencies` => [
    `auto` => [
        `types` => [
            'my-service.config' => [
                'typeOf' => Config::class,
            ],
        ],
    ],
],

then the factory for MyController is as expected but unfortunately also factory for my-service.config is created and replaced with the one configured in service-manager.

The correct result we can get if we have:

'dependencies' => [
    'auto' => [
        'types' => [
            MyController::class => [
                'parameters' => [
                    'config' => new Zend\Di\Resolver\TypeInjection('my-service.config'),
                ],
            ],
        ],
    ],
],

but this is not ideal (new instances in the static configuration).

Solution

We don't need to check type if typehint is class/interface and configuration is string.