christianblos/symfony-di-annotation

允许您通过注解配置 symfony 依赖注入

2.0.0 2020-07-31 10:15 UTC

This package is auto-updated.

Last update: 2024-08-29 04:37:08 UTC


README

该库是 Symfony DependencyInjection 组件 的扩展。它允许您通过注解直接在您的类中配置 DI 容器。

设置

1. 通过 composer 安装

composer require christianblos/symfony-di-annotation

2. 将编译器传递添加到 ContainerBuilder 中

<?php
use Symfony\Component\DependencyInjection\Annotation\Compiler\AnnotationPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;

$containerBuilder = new ContainerBuilder();

$srcDirs = ['path/to/classes']; // the path(s) to your classes which contain annotations

$containerBuilder->addCompilerPass(AnnotationPass::createDefault($srcDirs));

(有关 ContainerBuilder 的更多信息,请参阅 symfony 文档)

基本用法

只需将 @Service 注解添加到所有服务中,它们将自动注册到 DIC 中

<?php
use Symfony\Component\DependencyInjection\Annotation\Service;

/**
 * @Service
 */
class SomeRepository
{

}
<?php
use Symfony\Component\DependencyInjection\Annotation\Service;

/**
 * @Service(public=true)
 */
class SomeService
{
    public function __construct(SomeRepository $repo)
    {
        // $repo will be injected automatically
    }
}

现在您可以从容器中简单地检索服务

$someService = $container->get(SomeService::class);

注意: 如果您想配置同一类的两个服务,也可以添加多个 @Service 注解。然后您还需要设置服务的 id,如 @Service(id="myService"),因为您不能有两个具有相同 id 的服务(默认情况下,id 是完整类名)。

注入参数

您还可以通过将其添加到注解中注入参数

<?php
use Symfony\Component\DependencyInjection\Annotation\Service;

/**
 * @Service(
 *     inject={
 *         "someParam"="%foo%"
 *     }
 * )
 */
class SomeService
{
    public function __construct($someParam)
    {
        // - "someParam" ist the name of the variable
        // - "%foo%" means you want to inject the "foo" parameter from the container
    }
}

修改容器

可以使用方法注解修改整个容器。一个可能的用例是事件监听器。根据您的实现,它可能看起来像这样

class MyListener
{
    /**
     * @ListenTo(UserRegistered::class)
     */
    public function doSomethingWhenUserRegistered($event)
    {
    
    }
}

注意: 这只是可能实现的一个示例。此库中未实现 "ListenTo" 注解!请参阅 如何实现的示例

更多示例

您可以在 示例文件夹 中找到一些示例。