如何在 PHP-DI 的定义中使用 autowire(...)、create(...) 和 get(...)?
How to use autowire(...), create(...), and get(...) in definitions for PHP-DI?
PHP-DI 6 provides multiple functions, that working in the definitions。其中三个似乎在定义上下文中做同样的事情:autowire(...)
、create(...)
和 get(...)
。例如。我有以下类型:
FooServiceInterface
BarServiceInterface
FooAService implements FooServiceInterface
dependencies: BarServiceInterface $barService
FooBService implements FooServiceInterface
dependencies: BarServiceInterface $barService
BarService implements BarServiceInterface
dependencies: -
FooServiceInterface
被注入 Symfony 控制器(构造函数注入)。
现在我的文件定义为:
return [
FooServiceInterface::class => DI\autowire(FooBService::class),
BarServiceInterface::class => DI\autowire(BarService::class),
];
有效。
我也可以这样设置:
return [
FooServiceInterface::class => DI\get(FooBService::class),
BarServiceInterface::class => DI\get(BarService::class),
];
它还在工作。
这个
return [
FooServiceInterface::class => DI\create(FooBService::class),
BarServiceInterface::class => DI\create(BarService::class),
];
无效。
还有这个
return [
FooServiceInterface::class => DI\get(FooBService::class),
BarServiceInterface::class => DI\create(BarService::class),
];
会。
这三个函数有什么区别(在定义的上下文中)?推荐使用哪个函数来设置通用接口依赖定义(如SomeInterface::class => DI\recommendedFunction(SomeClass::class)
)?
我会说只有当你知道为什么需要它时才使用 get()
。
然后在 autowire()
和 create()
之间进行选择由您决定:您是否需要自动装配?
简单地使用 create()
就是告诉 PHP-DI 只需执行 new FooService()
即可创建服务。如果这足够了,那很好。如果您的服务有依赖项,您可以依赖自动装配(使用 autowire()
)或定义依赖项以使用 create()
手动注入。由你决定。
PHP-DI 6 provides multiple functions, that working in the definitions。其中三个似乎在定义上下文中做同样的事情:autowire(...)
、create(...)
和 get(...)
。例如。我有以下类型:
FooServiceInterface
BarServiceInterface
FooAService implements FooServiceInterface
dependencies: BarServiceInterface $barService
FooBService implements FooServiceInterface
dependencies: BarServiceInterface $barService
BarService implements BarServiceInterface
dependencies: -
FooServiceInterface
被注入 Symfony 控制器(构造函数注入)。
现在我的文件定义为:
return [
FooServiceInterface::class => DI\autowire(FooBService::class),
BarServiceInterface::class => DI\autowire(BarService::class),
];
有效。
我也可以这样设置:
return [
FooServiceInterface::class => DI\get(FooBService::class),
BarServiceInterface::class => DI\get(BarService::class),
];
它还在工作。
这个
return [
FooServiceInterface::class => DI\create(FooBService::class),
BarServiceInterface::class => DI\create(BarService::class),
];
无效。
还有这个
return [
FooServiceInterface::class => DI\get(FooBService::class),
BarServiceInterface::class => DI\create(BarService::class),
];
会。
这三个函数有什么区别(在定义的上下文中)?推荐使用哪个函数来设置通用接口依赖定义(如SomeInterface::class => DI\recommendedFunction(SomeClass::class)
)?
我会说只有当你知道为什么需要它时才使用 get()
。
然后在 autowire()
和 create()
之间进行选择由您决定:您是否需要自动装配?
简单地使用 create()
就是告诉 PHP-DI 只需执行 new FooService()
即可创建服务。如果这足够了,那很好。如果您的服务有依赖项,您可以依赖自动装配(使用 autowire()
)或定义依赖项以使用 create()
手动注入。由你决定。