Skip to content

组件扫描 ​

概述 ​

组件扫描(Component Scanning)是 Kuiper DI 模块的自动发现机制,它可以自动扫描指定命名空间下的类,识别带有组件注解的类,并将其注册到容器中。这大大减少了手动配置的工作量。

#[Component] 属性 ​

#[Component] 是标记组件的核心属性。

基本用法 ​

php
use kuiper\di\attribute\Service;

#[Service]
class UserService
{
    public function createUser(string $name): User
    {
        return new User($name);
    }
}

带名称的组件 ​

php
use kuiper\di\attribute\Component;
#[Component('userService')]
class UserService
{
    // ...
}

使用场景:当需要按名称获取组件时使用。

组件扫描配置 ​

配置扫描命名空间 ​

在 src/container.php 中配置:

php
return [
    'component_scan' => [
        'App\\Service',
        'App\\Repository',
        'App\\Controller',
    ],
];

使用 ContainerBuilder 配置 ​

php
use kuiper\di\ContainerBuilder;

$builder = new ContainerBuilder($classLoader, $config);

// 扫描单个命名空间
$builder->componentScan(['App\\Service']);

// 扫描多个命名空间
$builder->componentScan([
    'App\\Service',
    'App\\Repository',
]);

排除命名空间 ​

排除不需要扫描的命名空间 ​

php
// 排除测试类
$builder->componentScanExclude('App\\Tests');

// 排除多个命名空间
$builder->componentScanExclude('App\\Tests');
$builder->componentScanExclude('App\\Fixtures');
$builder->componentScanExclude('App\\Entity');

在配置文件中排除 ​

src/container.php 不支持排除配置

runtime/src/Runtime.php 读取 src/container.php 时只识别 configuration 与 component_scan 两个键。写 component_scan_exclude 既不会报错,也不会生效—— 被「排除」的测试替身类、fixtures 仍会被扫描进容器。

排除命名空间只能用编程式调用 ContainerBuilder::componentScanExclude():

php
use kuiper\di\ContainerBuilder;

$builder = new ContainerBuilder($classLoader, $config);
$builder->componentScan(['App\\']);
$builder->componentScanExclude('App\\Tests');
$builder->componentScanExclude('App\\Fixtures');
$builder->componentScanExclude('App\\Entity');

如果不通过 Runtime 启动(例如自建容器),可以自己读取配置文件再转成 ContainerBuilder 调用,但同样只有 component_scan / configuration 两个键有意义。

扫描机制 ​

ComponentScanner ​

ComponentScanner 是负责扫描组件的核心类。日常使用推荐通过 ContainerBuilder 的 componentScan() / componentScanExclude() 配置,由容器在 build() 阶段驱动扫描。

php
use kuiper\di\ContainerBuilder;
use kuiper\helper\Config;

// ContainerBuilder 需要 ClassLoader 与 Config 两个必填参数
$builder = new ContainerBuilder(
    require __DIR__.'/vendor/autoload.php',
    Config::create([])
);

// 添加需要扫描的命名空间
$builder->componentScan(['App\\Service', 'App\\Repository']);

// 添加排除命名空间(每次调用排除一个命名空间)
$builder->componentScanExclude('App\\Tests');

$container = $builder->build();

直接使用 ComponentScanner 时,构造函数需要 ClassLoader 与 ComponentCollection 两个必填参数,scan() 不接受参数、返回 void(扫描结果注册到 ComponentCollection):

php
use kuiper\di\ComponentScanner;
use kuiper\di\ComponentCollection;
use Composer\Autoload\ClassLoader;

$scanner = new ComponentScanner($classLoader, new ComponentCollection());

// 执行扫描(扫描范围由构造时传入的 namespacesToScan 决定)
$scanner->scan();

识别的属性类型 ​

默认识别以下属性:

属性说明
kuiper\di\attribute\ComponentKuiper 组件属性。扫描时按 IS_INSTANCEOF 匹配,#[Service]、#[Cacheable] 等子类同样会被识别
Symfony\Component\Console\Attribute\AsCommandSymfony Console 命令属性

自定义属性只要**继承 kuiper\di\attribute\Component**就会被自动识别, 无需任何注册。仓库内的例子:

  • kuiper\cache\attribute\Cacheable(继承 Component,实现 PureMetadataComponentInterface)
  • kuiper\rpc\attribute\RpcService / kuiper\rpc\attribute\RpcClient(继承 Component,实现 MetadataComponentInterface)
  • kuiper\http\client\attribute\HttpClient(继承 Component,实现 MetadataComponentInterface)

纯元数据属性(PureMetadataComponentInterface) ​

标记接口上的属性(如 #[RpcClient])不对应可实例化的对象,这类属性实现 kuiper\di\MetadataComponentInterface。如果标注的类本身是可实例化的具体类 (例如 #[Cacheable] 标注的 DTO),属性还需要实现更严格的 kuiper\di\PureMetadataComponentInterface,否则该 DTO 会被当成普通组件注册进容器:

  • DTO 变成可注入的 Bean(业务代码可以意外注入它);
  • 多个标注 DTO 实现同一接口时,容器会抛 InvalidAttribute: Ambiguous components for interface ...。
php
use kuiper\di\attribute\Component;
use kuiper\di\PureMetadataComponentInterface;

// 纯标记属性:只做标注,不产生对象
#[Attribute(\Attribute::TARGET_CLASS)]
final class Cacheable extends Component implements PureMetadataComponentInterface
{
}

#[Cacheable]
final class UserDto
{
    public function __construct(public readonly string $name)
    {
    }
}

一句话规则

  • 只做标记、不希望标注类进容器 → 属性继承 Component 并实现 PureMetadataComponentInterface;
  • 标注类本身就是要放进容器的服务 → 属性继承 Component 并实现 MetadataComponentInterface(或不实现任何标记接口)。

注册自定义组件属性 ​

ComponentScanner::register() 已废弃

ComponentScanner::register() 已标注 @deprecated:它维护一个进程级可变的静态 全局数组,仓库内外均无调用方;扫描注解集合应当保持不可变。框架当前没有等价的 公开扩展点,如确有扩展需求请提出 issue 增加构造参数。

推荐做法是让自定义属性继承 kuiper\di\attribute\Component——扫描器按 IS_INSTANCEOF 匹配,会自动识别,无需注册:

php
use kuiper\di\attribute\Component;

// 继承 Component 即可被自动扫描到
#[Attribute(\Attribute::TARGET_CLASS)]
final class MyCustomAttribute extends Component
{
}

纯标记属性请额外实现 PureMetadataComponentInterface(见上文)。

组件注册流程 ​

1. 扫描阶段 ​

text
扫描命名空间 → 加载类文件 → 检查属性 → 创建组件定义

2. 注册阶段 ​

php
use kuiper\di\ComponentCollection;

// 组件自动注册到 ComponentCollection
ComponentCollection::register($component);

3. 容器构建阶段 ​

php
// 扫描组件
$builder->componentScan(['App\\Service']);

// 构建容器(自动注册所有扫描到的组件)
$container = $builder->build();

组件类型 ​

普通组件 ​

php
use kuiper\di\attribute\Service;
#[Service]
class EmailService
{
    public function send(string $to, string $subject): void
    {
        // 发送邮件逻辑
    }
}

配置组件 ​

php

#[Configuration]
class AppConfiguration
{
    // 配置类也是组件
}

控制器组件 ​

php
use kuiper\web\attribute\Controller;

#[Controller]  // 继承自 #[Component]
class UserController
{
    // 控制器自动注册为组件
}

组件命名 ​

默认命名规则 ​

默认情况下,组件使用其完全限定类名作为标识:

php
use kuiper\di\attribute\Service;
#[Service]
class UserService
{
    // 组件名称:App\Service\UserService
}

// 获取组件
$service = $container->get(\App\Service\UserService::class);

自定义组件名称 ​

php
use kuiper\di\attribute\Component;
#[Component('userService')]
class UserService
{
    // 组件名称:userService
}

// 获取组件
$service = $container->get('userService');

接口绑定 ​

php
use kuiper\di\attribute\Service;
#[Service]
class UserService implements UserServiceInterface
{
    // 可以通过接口类型获取
}

// 通过接口获取
$service = $container->get(UserServiceInterface::class);

依赖注入 ​

构造器注入 ​

php
use kuiper\di\attribute\Component;
#[Component]
class UserController
{
    public function __construct(
        private readonly UserService $userService  // 自动注入
    ) {
    }
}

属性注入 ​

php
use kuiper\di\attribute\Component;
use DI\Attribute\Inject;

#[Component]
class UserController
{
    #[Inject]
    private UserService $userService;  // 属性注入
}

Setter 注入 ​

php
use kuiper\di\attribute\Component;
#[Component]
class UserController
{
    private UserService $userService;

    #[Inject]
    public function setUserService(UserService $userService): void
    {
        $this->userService = $userService;
    }
}

扫描最佳实践 ​

1. 分层扫描 ​

php
$builder->componentScan([
    'App\Controller',  // 控制器层
    'App\Service',     // 服务层
    'App\Repository',  // 数据访问层
]);

2. 排除非组件类 ​

php
// componentScanExclude() 每次只接受单个命名空间(签名:string $namespace),链式调用
$builder
    ->componentScanExclude('App\Tests')      // 测试类
    ->componentScanExclude('App\Fixtures')   // 测试数据
    ->componentScanExclude('App\Entity');    // 实体类(通常不需要注入)

3. 按功能模块组织 ​

php
$builder->componentScan([
    'App\User',          // 用户模块
    'App\Product',       // 产品模块
    'App\Order',         // 订单模块
]);

4. 使用接口定义 ​

php
use kuiper\di\attribute\Service;
// 接口
interface UserRepositoryInterface
{
    public function find(int $id): ?User;
}

// 实现
#[Service]
class UserRepository implements UserRepositoryInterface
{
    public function find(int $id): ?User
    {
        // ...
    }
}

性能优化 ​

1. 限制扫描范围 ​

php
// 不推荐:扫描整个应用命名空间
$builder->componentScan(['App\\']);

// 推荐:只扫描需要的命名空间
$builder->componentScan([
    'App\\Service',
    'App\\Repository',
]);

2. 排除不需要的目录 ​

php
// componentScanExclude() 每次只接受单个命名空间,链式调用
$builder
    ->componentScanExclude('App\\Tests')
    ->componentScanExclude('App\\Fixtures')
    ->componentScanExclude('App\\DTO');

3. 使用缓存 ​

在生产环境中,组件扫描结果会被缓存,避免重复扫描。

调试组件扫描 ​

查看已注册组件 ​

第二个参数不能省

ComponentCollection::getComponents($componentClass, $flags = 0) 的第 2 个参数默认 0, 表示精确匹配属性类名:这样只能取到用 #[Component] 本身标注的组件, #[Service](Component 的子类)会被漏掉。要包含子类,必须传 \ReflectionAttribute::IS_INSTANCEOF。

php
use kuiper\di\ComponentCollection;
use kuiper\di\attribute\Component;

// 获取所有已注册的组件(getComponents 的第 1 个参数必填:组件 attribute 类)
// 传 IS_INSTANCEOF 才会把 #[Service] 等子类属性的组件一并返回
$components = ComponentCollection::getComponents(
    Component::class,
    \ReflectionAttribute::IS_INSTANCEOF
);

foreach ($components as $component) {
    echo $component->getComponentClass()->getName() . "\n";
}

静态方法 vs 实例方法

ComponentCollection::getComponents() 读的是单例(ComponentCollection::getInstance()), 容器 build() 时会把扫描结果写入该单例。 如果你是自己 new ComponentCollection() 并直接传给 ComponentScanner, 请改用实例方法 $collection->get(Component::class, \ReflectionAttribute::IS_INSTANCEOF)。

检查特定组件 ​

php
$components = ComponentCollection::getComponents(
    Component::class,
    \ReflectionAttribute::IS_INSTANCEOF
);

foreach ($components as $component) {
    $className = $component->getComponentClass()->getName();
    // 方法名是 getComponentAttribute()(不是 getAttribute())
    $attribute = $component->getComponentAttribute();

    echo "Component: $className\n";
    // Component attribute 的 name 是 public readonly 属性 $value
    if ($attribute instanceof Component && null !== $attribute->value) {
        echo "Name: " . $attribute->value . "\n";
    }
}

常见问题 ​

1. 组件未被扫描到 ​

问题:组件类存在但容器中找不到

解决方案:

  • 确认类有 #[Component] 属性
  • 确认类在扫描的命名空间内
  • 确认类没有被排除

2. 命名空间错误 ​

问题:组件类无法加载

解决方案:

  • 检查命名空间是否正确
  • 确认 Composer 自动加载配置正确
  • 运行 composer dump-autoload

3. 循环依赖 ​

问题:组件之间存在循环依赖

解决方案:

  • 重构代码,消除循环依赖
  • 使用延迟注入(DI\get())
  • 引入中间服务解耦

相关文档 ​

基于 MIT 许可发布