1

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))?

automatix
  • 14,018
  • 26
  • 105
  • 230

1 Answers1

2

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.

Matthieu Napoli
  • 48,448
  • 45
  • 173
  • 261
  • How autowiring impact performance? Taking convenience aside (which makes autowiring a better choice), is there any benefit in using PHP definitions vs autowiring, especially from a performance perspective? – Belkin Dec 06 '19 at 22:09
  • Found a relevant response here - https://github.com/PHP-DI/PHP-DI/issues/731 – Alexander Kucheryuk Dec 12 '20 at 23:31
  • For performances, read the documentation: https://php-di.org/doc/performances.html Don't read issues, they can be outdated. – Matthieu Napoli Dec 14 '20 at 08:06