PHP-DI 6 provides multiple functions, that working in the definitions. Three of them seem to do the same in the definitions context: autowire(...)
, create(...)
, and get(...)
. E.g. I have following types:
FooServiceInterface
BarServiceInterface
FooAService implements FooServiceInterface
dependencies: BarServiceInterface $barService
FooBService implements FooServiceInterface
dependencies: BarServiceInterface $barService
BarService implements BarServiceInterface
dependencies: -
The FooServiceInterface
gets injected into a Symfony controller (constructor injection).
Now my file with the definitions:
return [
FooServiceInterface::class => DI\autowire(FooBService::class),
BarServiceInterface::class => DI\autowire(BarService::class),
];
It works.
I also can set it up like this:
return [
FooServiceInterface::class => DI\get(FooBService::class),
BarServiceInterface::class => DI\get(BarService::class),
];
And it's still working.
This
return [
FooServiceInterface::class => DI\create(FooBService::class),
BarServiceInterface::class => DI\create(BarService::class),
];
doesn't work.
And this
return [
FooServiceInterface::class => DI\get(FooBService::class),
BarServiceInterface::class => DI\create(BarService::class),
];
does.
What is the difference between the three functions (in the context of definitions)? Which one is the recommended function to set up a common interface dependency definition (like SomeInterface::class => DI\recommendedFunction(SomeClass::class)
)?
I would say use get()
only if you know why you would need it.
Then to choose between autowire()
and create()
is up to you: do you need autowiring or not?
Using simply create()
is telling PHP-DI to just do new FooService()
to create the service. If that's enough, then fine. If your service has dependencies, you can either rely on autowiring (using autowire()
) or define the dependencies to inject manually using create()
. It's up to you.