<?php
declare(strict_types=1);
namespace App\Support\Attributes;
#[\Attribute(\Attribute::TARGET_PROPERTY)]
readonly class Injection
{
public function __construct(
public ?string $propertyType = null,
public array $parameters = []
) {}
}
引导解析注解
<?php
declare(strict_types=1);
namespace App\Providers;
use App\Support\Attributes\Injection;
use Illuminate\Foundation\Application;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register(): void {}
public function boot(): void
{
$this->injection();
}
private function injection(): void
{
$this->app->resolving(static function (mixed $object, Application $app): void {
if (! \is_object($object)) {
return;
}
$class = str($object::class);
if (
! $class->is(config('services.injection.only'))
|| $class->is(config('services.injection.except'))
) {
return;
}
$reflectionObject = new \ReflectionObject($object);
foreach ($reflectionObject->getProperties() as $reflectionProperty) {
if (! $reflectionProperty->isDefault() || $reflectionProperty->isStatic()) {
continue;
}
$attributes = $reflectionProperty->getAttributes(Injection::class);
if ($attributes === []) {
continue;
}
/** @var Injection $injection */
$injection = $attributes[0]->newInstance();
$propertyType = value(static function () use ($injection, $reflectionProperty, $reflectionObject): string {
if ($injection->propertyType) {
return $injection->propertyType;
}
$reflectionPropertyType = $reflectionProperty->getType();
if ($reflectionPropertyType instanceof \ReflectionNamedType && ! $reflectionPropertyType->isBuiltin()) {
return $reflectionPropertyType->getName();
}
throw new \LogicException(\sprintf(
'Attribute [%s] of %s miss a argument, or %s must be a non-built-in named type.',
Injection::class,
$property = "property [{$reflectionObject->getName()}::\${$reflectionProperty->getName()}]",
$property,
));
});
$reflectionProperty->isPublic() or $reflectionProperty->setAccessible(true);
$reflectionProperty->setValue($object, $app->make($propertyType, $injection->parameters));
}
});
}
}
laravel 中实现注解注入
创建注解类
引导解析注解
配置解析范围(可选)
config/services.php
使用
示例
输出
与依赖注入比较
相关连接
原文连接