高级特性
概述
Kuiper DI 模块提供了一系列高级特性,用于处理复杂的依赖管理场景。本节介绍循环依赖处理、配置依赖、代理生成等高级功能。
循环依赖检测
自动检测
Kuiper DI 模块内置了循环依赖检测机制。
前置条件
#[Configuration(dependsOn: [...])] 指向的配置类必须真实存在并实现 kuiper\di\DefinitionConfiguration,否则 ContainerBuilder 会先抛 InvalidArgumentException(配置类不存在 / 未实现接口),走不到循环依赖检测。
use kuiper\di\DefinitionConfiguration;
#[Configuration(dependsOn: [ConfigurationB::class])]
class ConfigurationA implements DefinitionConfiguration
{
#[Bean]
public function serviceA(ServiceB $serviceB): ServiceA
{
return new ServiceA($serviceB);
}
public function getDefinitions(): array
{
return [];
}
}
#[Configuration(dependsOn: [ConfigurationA::class])]
class ConfigurationB implements DefinitionConfiguration
{
#[Bean]
public function serviceB(ServiceA $serviceA): ServiceB
{
return new ServiceB($serviceA); // 循环依赖!
}
public function getDefinitions(): array
{
return [];
}
}结果:抛出 RuntimeException 异常
Circular dependency detected in configuration classes: ConfigurationA -> ConfigurationB -> ConfigurationA解决循环依赖
1. 重构设计(推荐)
问题场景:订单服务与库存服务的循环依赖
在引入事件系统之前,OrderService 和 InventoryService 可能这样设计:
use kuiper\di\attribute\Service;
#[Service]
class OrderService
{
public function __construct(
private readonly InventoryService $inventoryService // 依赖库存服务
) {}
public function createOrder(array $data): Order
{
$order = new Order($data);
$this->inventoryService->reserveStock($order); // 创建订单时调用库存
return $order;
}
}
#[Service]
class InventoryService
{
public function __construct(
private readonly OrderService $orderService // 依赖订单服务
) {}
public function checkStock(string $productId): bool
{
// 查询该产品的订单数量来计算可用库存
$reservedCount = $this->orderService->getReservedCount($productId);
return $this->stock[$productId] > $reservedCount;
}
}依赖链:OrderService → InventoryService → OrderService → ...
结果:容器无法确定先创建哪个服务,抛出循环依赖异常。
重构方案:引入事件系统解耦
use kuiper\di\attribute\Service;
// 引入事件系统解耦
interface OrderCreatedListener
{
public function onOrderCreated(Order $order): void;
}
#[Service]
class InventoryService implements OrderCreatedListener
{
public function onOrderCreated(Order $order): void
{
// 处理库存
}
}
#[Service]
class OrderService
{
public function __construct(
private readonly EventDispatcher $dispatcher
) {
}
public function createOrder(array $data): Order
{
$order = new Order($data);
$this->dispatcher->dispatch(new OrderCreatedEvent($order));
return $order;
}
}依赖链:OrderService → EventDispatcher,InventoryService → EventDispatcher
优势:
- 彻底消除循环依赖,从根源解决问题
- OrderService 不再直接依赖 InventoryService
- 库存服务作为事件监听器,可独立测试和维护
- 支持多个监听器响应同一事件(如通知服务、积分服务等)
2. 使用延迟注入
#[Configuration]
class ServiceConfiguration
{
#[Bean]
public function serviceA(ContainerInterface $container): ServiceA
{
return new ServiceA(function () use ($container) {
return $container->get(ServiceB::class);
});
}
#[Bean]
public function serviceB(ServiceA $serviceA): ServiceB
{
return new ServiceB($serviceA);
}
}3. 使用 Setter 注入
use kuiper\di\attribute\Component;
#[Component]
class ServiceA
{
private ?ServiceB $serviceB = null;
#[Inject]
public function setServiceB(ServiceB $serviceB): void
{
$this->serviceB = $serviceB;
}
}
#[Component]
class ServiceB
{
public function __construct(
private readonly ServiceA $serviceA
) {
}
}配置依赖管理
dependsOn 属性
#[Configuration] 的 dependsOn 属性确保配置类按正确顺序加载。
#[Configuration]
class DatabaseConfiguration
{
#[Bean('db.connection')]
public function connection(): Connection
{
return new Connection('localhost', 3306);
}
}
#[Configuration(dependsOn: [DatabaseConfiguration::class])]
class RepositoryConfiguration
{
#[Bean]
public function userRepository(
#[Inject('db.connection')] Connection $connection
): UserRepository {
return new UserRepository($connection);
}
}多依赖配置
#[Configuration(dependsOn: [
DatabaseConfiguration::class,
CacheConfiguration::class,
LoggerConfiguration::class
])]
class ServiceConfiguration
{
// 可以依赖所有上述配置的 Bean
}验证配置依赖
#[Configuration(dependsOn: [NonExistentConfig::class])]
class MyConfiguration
{
// 如果 NonExistentConfig 不存在或不实现 DefinitionConfiguration
// 将抛出 InvalidArgumentException
}代理与延迟加载
延迟加载概念
延迟加载允许对象在实际使用时才创建,而不是在注入时创建。
启用代理缓存
// 开发环境
$builder->writeProxiesToFile(false);
// 生产环境(仅 PHP < 8.4)
$builder->writeProxiesToFile(true, 'tmp/proxies');PHP >= 8.4 不支持写代理文件
PHP 8.4 起 PHP-DI 使用原生惰性代理(DI\Proxy\NativeProxyFactory),代理永不落盘。 ContainerBuilder::writeProxiesToFile(true, $dir) 在 PHP >= 8.4 上会直接抛 InvalidArgumentException(见 di/src/ContainerBuilder.php)。
PHP 8.4+ 请保持 writeProxiesToFile(false)(默认值)或不调用该方法。
延迟注入
use function DI\create;
$builder->addDefinitions([
HeavyService::class => create(HeavyService::class)
->lazy(), // 延迟创建
]);代理对象
use kuiper\di\attribute\Service;
#[Service]
class LazyService
{
public function __construct(
private readonly HeavyInterface $heavy // 可能是代理对象
) {
}
public function doWork(): void
{
// 首次调用 $heavy->method() 时才真正创建 HeavyService
$this->heavy->method();
}
}Bean 感知注入
自定义注入策略
Bean 感知注入允许为实现了特定感知接口的组件自动注入 Bean。使用 BeanAwareInjection::create() 方法创建注入策略:
use kuiper\di\BeanAwareInjection;
use Psr\Log\LoggerAwareInterface;
// 创建感知接口的注入策略(接口必须真实存在)
$injection = BeanAwareInjection::create(LoggerAwareInterface::class);
$builder->addBeanAwareInjection($injection);感知接口规范
感知接口必须满足以下条件:
- 只有一个公共方法(通常是 setter)
- 该方法只有一个类类型参数(不能是内置类型)
// 正确的感知接口定义
interface CacheAwareInterface
{
public function setCache(CacheInterface $cache): void;
}
// 错误示例:多个方法
interface BadAwareInterface
{
public function setCache(CacheInterface $cache): void;
public function setLogger(LoggerInterface $logger): void; // 不允许
}
// 错误示例:无类型参数
interface AnotherBadAwareInterface
{
public function setCache($cache): void; // 缺少类型声明
}使用场景
use kuiper\di\attribute\Service;
// 定义感知接口
interface CacheAwareInterface
{
public function setCache(CacheInterface $cache): void;
}
#[Configuration]
class CacheConfiguration
{
#[Bean]
public function cache(): CacheInterface
{
return new RedisCache('redis://localhost');
}
}
// 注册感知注入
$builder->addBeanAwareInjection(
BeanAwareInjection::create(CacheAwareInterface::class)
);
// 实现感知接口的组件会自动注入 CacheInterface
#[Service]
class UserService implements CacheAwareInterface
{
private CacheInterface $cache;
public function setCache(CacheInterface $cache): void
{
$this->cache = $cache;
}
public function getUser(int $id): ?User
{
return $this->cache->get("user:$id");
}
}限制说明
通过 #[Bean] 注解添加的 Bean 使用 FactoryDefinition 定义,不支持 Bean 感知注入。这是因为感知注入依赖于 ObjectDefinition 来获取类名并进行方法注入,而 FactoryDefinition 没有对应的类信息。
如果需要在 Bean 方法中使用感知接口,需要直接在方法参数中声明依赖:
#[Configuration]
class UserConfiguration
{
#[Bean]
public function userService(CacheInterface $cache): UserService
{
$service = new UserService();
$service->setCache($cache);
return $service;
}
}容器包装
包装容器
use Psr\Container\ContainerInterface;
$wrapperContainer = new class implements ContainerInterface {
public function get(string $id)
{
// 自定义获取逻辑
return null;
}
public function has(string $id): bool
{
return false;
}
};
$builder->wrapContainer($wrapperContainer);使用场景
- 与其他容器集成
- 实现自定义查找逻辑
- 添加缓存层
动态定义
运行时添加定义
// 注意:容器构建后无法添加定义
// 必须在 build() 之前添加,否则抛 LogicException:
// The ContainerBuilder cannot be modified after the container has been built
$builder->addDefinitions([
'dynamic.service' => DI\create(DynamicService::class),
]);
$container = $builder->build();条件化定义
$builder->addDefinitions([
CacheInterface::class => function (ContainerInterface $c) {
$config = $c->get('config');
if ($config->get('cache.driver') === 'redis') {
return new RedisCache($config->get('cache.redis'));
}
return new ArrayCache();
},
]);环境感知配置
不同环境的不同配置
use kuiper\helper\ConfigAwareInterface;
use kuiper\helper\ConfigInterface;
#[Configuration]
class EnvironmentAwareConfiguration implements ConfigAwareInterface
{
private ConfigInterface $config;
// 配置类由容器用 new 无参实例化(不走容器),所以不能靠构造器注入,
// 否则会抛 ArgumentCountError。
// 实现 ConfigAwareInterface 后,框架会在装配时注入配置对象。
public function setConfig(ConfigInterface $config): void
{
$this->config = $config;
}
#[Bean]
public function cache(): CacheInterface
{
$environment = $this->config->get('app.env');
return match ($environment) {
'prod' => new RedisCache('redis://prod'),
'dev' => new ArrayCache(),
'test' => new ArrayCache(),
default => throw new \InvalidArgumentException("Unknown environment: {$environment}"),
};
}
}配置文件分离
// config/di.php
return [
CacheInterface::class => match (getenv('APP_ENV')) {
'production' => DI\create(RedisCache::class),
default => DI\create(ArrayCache::class),
},
];编译容器
生产环境优化
use kuiper\di\ContainerBuilder;
$builder = new ContainerBuilder($classLoader, $config);
// 生产环境优化
$builder->useAutowiring(true)
->useAttributes(true);
if (\PHP_VERSION_ID < 80400) {
// 仅 PHP < 8.4 能把代理类写到磁盘;PHP >= 8.4 调用会抛 InvalidArgumentException
$builder->writeProxiesToFile(true, 'tmp/proxies');
}
$container = $builder->build();PHP >= 8.4 请勿写代理文件
PHP 8.4 起代理使用原生惰性加载,永不落盘,详见上文「启用代理缓存」。
性能考虑
- 开发环境:禁用代理缓存,便于调试
- 生产环境(PHP < 8.4):启用代理缓存,提高性能
- PHP >= 8.4:代理缓存不可用,只能关闭
容器继承
创建子容器
$parentContainer = $parentBuilder->build();
$childBuilder = new ContainerBuilder($classLoader, $config);
$childBuilder->wrapContainer($parentContainer);
$childContainer = $childBuilder->build();使用场景
- 模块化应用
- 测试隔离
- 多租户系统
属性处理器
自定义属性处理
ComponentScanner::register() 已废弃
该方法已标注 @deprecated:它维护一个进程级可变的静态全局数组,仓库内外均无调用方; 扫描注解集合应当保持不可变。框架当前没有等价的公开扩展点, 如确有扩展需求请提出 issue 增加构造参数。
推荐做法:让自定义属性继承 kuiper\di\attribute\Component。 扫描器按 IS_INSTANCEOF 匹配,会自动识别,无需注册。
use kuiper\di\attribute\Component;
// 继承 Component 即可被自动扫描为组件
#[Attribute(\Attribute::TARGET_CLASS)]
final class MyCustomAttribute extends Component
{
}
#[MyCustomAttribute]
class CustomComponent
{
// 将被扫描为组件
}纯元数据属性(PureMetadataComponentInterface)
如果自定义属性只做标记、不希望标注类进入容器(例如 #[Cacheable] 标注的 DTO), 属性类还需要实现 kuiper\di\PureMetadataComponentInterface:
use kuiper\di\attribute\Component;
use kuiper\di\PureMetadataComponentInterface;
// 纯标记属性:标注类不会注册为容器 Bean
#[Attribute(\Attribute::TARGET_CLASS)]
final class Cacheable extends Component implements PureMetadataComponentInterface
{
}
#[Cacheable]
final class UserDto
{
public function __construct(public readonly string $name)
{
}
}不实现 PureMetadataComponentInterface 时,可实例化的标注类会被注册成容器 Bean: 它变成可注入的 Bean,多个标注类实现同一接口时还会触发 InvalidAttribute: Ambiguous components for interface ...。
对照关系:
| 属性的用途 | 属性类应实现 | 标注类的结果 |
|---|---|---|
| 只做标记(DTO、缓存白名单等) | PureMetadataComponentInterface | 不进容器 |
| 标注类本身就是要注入的服务 | MetadataComponentInterface(或不实现) | 进容器 |
定义源优先级
多定义源
// 添加顺序决定优先级
$builder->addDefinitions('config/base.php'); // 优先级最低
$builder->addDefinitions('config/override.php'); // 可以覆盖 base
$builder->addDefinitions([ // 优先级最高
SomeService::class => DI\create(SomeService::class),
]);覆盖规则
// config/base.php
return [
CacheInterface::class => DI\create(ArrayCache::class),
];
// config/override.php
return [
CacheInterface::class => DI\create(RedisCache::class), // 覆盖 base
];调试技巧
查看已注册的定义
$container = $builder->build();
// 检查服务是否存在
if ($container->has(UserService::class)) {
echo "UserService is registered\n";
}
// 获取并检查
$service = $container->get(UserService::class);
var_dump(get_class($service));追踪依赖图
#[Configuration]
class DebugConfiguration
{
#[Bean]
public function serviceA(ServiceB $serviceB): ServiceA
{
echo "Creating ServiceA with ServiceB\n";
return new ServiceA($serviceB);
}
#[Bean]
public function serviceB(ServiceC $serviceC): ServiceB
{
echo "Creating ServiceB with ServiceC\n";
return new ServiceB($serviceC);
}
}检查代理对象
PHP-DI 7.x 没有 DI\Proxy\Proxy 类
vendor/php-di/php-di/src/Proxy/ 下只有 ProxyFactory、ProxyFactoryInterface 和 NativeProxyFactory,不存在 DI\Proxy\Proxy。 $service instanceof \DI\Proxy\Proxy 恒为 false,不能用来判断代理。
代理实例要按 PHP 版本分别识别:
前提
->lazy() 需要 PHP-DI 的懒加载支持:PHP 8.4+ 由原生惰性代理实现,开箱可用; PHP 8.4 以下需要额外安装 friendsofphp/proxy-manager-lts(PHP-DI 的可选依赖), 否则创建代理时会抛 RuntimeException: The ocramius/proxy-manager library is not installed。
// 容器里以 lazy() 定义的服务,取出来的就是代理对象
$heavy = $container->get(HeavyService::class);
if (\PHP_VERSION_ID >= 80400) {
// PHP 8.4+:NativeProxyFactory 生成原生惰性代理,
// get_class() 仍是目标类,要用 Reflection 判断是否尚未初始化
// (ReflectionClass::isUninitializedLazyObject() 需要 PHP 8.4+)
$isProxy = (new \ReflectionObject($heavy))->isUninitializedLazyObject();
} else {
// PHP 8.4 以下:由 ProxyManager 生成代理类,代理类继承自目标类
$isProxy = get_parent_class($heavy) === HeavyService::class;
}
if ($isProxy) {
echo "This is a proxy object\n";
echo "Real class: " . HeavyService::class . "\n";
}最佳实践
1. 避免循环依赖
// 不推荐
class A { public function __construct(private B $b) {} }
class B { public function __construct(private A $a) {} }
// 推荐:重构设计
class A { public function __construct(private EventDispatcher $dispatcher) {} }
class B implements EventListener { /* ... */ }2. 使用配置依赖管理加载顺序
#[Configuration(dependsOn: [DatabaseConfiguration::class])]
class RepositoryConfiguration
{
// 确保 DatabaseConfiguration 先加载
}3. 生产环境启用代理缓存
PHP >= 8.4 不支持
PHP >= 8.4 上 writeProxiesToFile(true, ...) 会抛 InvalidArgumentException, 请加版本判断。
if ($config->get('app.env') === 'production' && \PHP_VERSION_ID < 80400) {
$builder->writeProxiesToFile(true, 'tmp/proxies');
}4. 合理使用延迟加载
// 重型服务使用延迟加载
$builder->addDefinitions([
HeavyService::class => create(HeavyService::class)->lazy(),
]);5. 组织配置文件
// 按环境和模块组织
config/
├── di/
│ ├── base.php
│ ├── dev.php
│ ├── production.php
│ ├── database.php
│ └── cache.php