Search code examples
phpdependency-injectiondependency-propertiesphp-di

Using PHP-DI to inject variables into class methods automatically


I have been using PHP-DI and i wanted to enquire if there is a way to inject variables into various class methods automatically ie using autowiring.

Thanks


Solution

  • You could use annotations, but that means you would have to annotate every method so it might not be as "automatic" as you hope.

    You could also create a definition using wildcards:

    return [
        'MyProject\Controller\*' => DI\object()
            ->method('setSomething', DI\get('Foo')),
    ];
    

    But honestly I would recommend not doing that and rather write injections manually. This is more explicit and easier to understand when re-reading the code 6 months later, or when a co-worker joins the project.