cleancode / injectable-bundle
Injectable-bundle 负责将对象数组注入到您的类中。通过标记,您可以标记一个服务以注入到目标服务中。
1.0.1
2017-02-26 17:34 UTC
Requires
- php: >=7.0.0
- symfony/framework-bundle: ~3.0
This package is auto-updated.
Last update: 2024-08-29 04:31:16 UTC
README
描述
Injectable-bundle
负责将对象数组注入到您的类中。通过标记,您可以标记一个服务以注入到目标服务中。
示例使用 JMSDiExtraBundle,但您也可以通过 services.yml
轻松配置它
目标服务
/**
* @DI\Service("template_factory")
*/
class TemplateFactory
{
/**
* @param array|Template[] $providers
*/
private $providers;
/**
* @DI\InjectParams({
* "providers" = @DI\Inject("%empty_array%")
* })
*/
public function __construct(array $providers)
{
$this->providers = $providers;
}
public function createFor(string $type) : Template
{
foreach ($this->providers as $provider) {
if ($provider->isHandling($type)) {
return $provider;
}
}
throw new \Exception("Template for {$type} doesn't exists!");
}
}
interface Template
{
public function render() : string
public function isHandling(string $type) : bool;
}
注入服务
/**
* @DI\Service()
* @DI\Tag(name="injectable", attributes={"to"="template_factory", "index"="0"})
*/
class NiceTemplate implements Template
{
public function render()
{
return "nice template";
}
public function isHandling(string $type) : bool
{
return $type === 'nice';
}
}
/**
* @DI\Service()
* @DI\Tag(name="injectable", attributes={"to"="template_factory", "index"="0"})
*/
class UglyTemplate implements Template
{
public function render()
{
return "ugly template";
}
public function isHandling(string $type) : bool
{
return $type === 'ugly';
}
}
上述服务将被注入到 TemplateFactory。
如果没有标记为可注入的服务用于 template_factory
,模板工厂将使用空数组。
理解注解
@DI\Tag(name="injectable", attributes={"to"="template_factory", "index"="0"})
name="injectable"
- 标记服务由 InjectableBundle 使用
"to"="template_factory"
- 设置目标服务"index"="0"
- 设置目标服务构造函数参数索引