dotkernel / dot-annotated-services
使用类属性的DotKernel依赖注入组件。
Requires
- php: ~8.2.0 || ~8.3.0
- doctrine/orm: ^2.9 || ^3.0
- psr/container: ^1.0 || ^2.0
Requires (Dev)
- laminas/laminas-coding-standard: ^2.5
- phpunit/phpunit: ^10.5
- vimeo/psalm: ^5.20
README
DotKernel依赖注入服务。
此包可以通过去除所有只是为了注入依赖项而编写的工厂来清理您的代码。
安装
在您的项目目录中运行以下命令来安装dot-annotated-services
composer require dotkernel/dot-annotated-services
安装后,通过在您的配置聚合(通常是config/config.php
)中添加以下行来在您的项目中注册dot-annotated-services
Dot\AnnotatedServices\ConfigProvider::class,
用法
使用AttributedServiceFactory
您可以使用AttributedServiceFactory
在服务管理器中注册服务,如下例所示
return [
'factories' => [
ServiceClass::class => AttributedServiceFactory::class,
],
];
注意
您只能使用完全限定类名作为服务键
下一步是在服务构造函数中添加#[Inject]
属性,并指定要注入的服务FQCN
use Dot\AnnotatedServices\Attribute\Inject;
#[Inject(
App\Srevice\Dependency1::class,
App\Srevice\Dependency2::class,
"config",
)]
public function __construct(
protected App\Srevice\Dependency1 $dep1,
protected App\Srevice\Dependency2 $dep2,
protected array $config
) {
}
#[Inject]
属性告诉AttributedServiceFactory
注入作为参数指定的服务。应提供有效的服务名称,如服务管理器中注册的那样。
要从服务管理器注入数组值,您可以使用以下点表示法
use Dot\AnnotatedServices\Attribute\Inject;
#[Inject(
"config.debug",
)]
这将注入$container->get('config')['debug'];
。
注意
即使使用点表示法,
AttributedServiceFactory
也会首先检查是否存在具有该名称的服务名称。
使用AttributedRepositoryFactory
您可以使用以下方式使用AttributedRepositoryFactory
注册doctrine存储库并将它们注入
return [
'factories' => [
ExampleRepository::class => AttributedRepositoryFactory::class,
],
];
下一步是在存储库类中添加#[Entity]
属性。
“name”字段必须是完全限定类名。
每个存储库都应该扩展Doctrine\ORM\EntityRepository
。
use Api\App\Entity\Example;
use Doctrine\ORM\EntityRepository;
use Dot\AnnotatedServices\Attribute\Entity;
#[Entity(name: Example::class)]
class ExampleRepository extends EntityRepository
{
}
注意
从dot-annotated-services
的版本5.0
开始
- 服务只能使用
#[Inject]
属性注入(不再支持@Inject
和@Service
注解) - 只能使用
#[Entity]
属性建立存储库-实体关系(不再支持@Entity
注解) - 通过
#[Entity]
/#[Inject]
属性注入的依赖项不会被缓存 - 不再支持将依赖项注入到属性设置器中