Skip to content

属性系统 ​

Kuiper 框架全面采用 PHP 8 的属性(Attributes)系统进行声明式配置,替代传统的 DocBlock 注解。属性系统提供了类型安全、IDE 支持和更好的性能。

什么是属性?

属性(Attributes)是 PHP 8 引入的原生元数据声明机制,类似于 Java 的注解或 Python 的装饰器。它允许在类、方法、属性等代码结构上添加结构化的元数据,框架可以通过反射读取这些元数据进行相应的处理。

什么是 PHP 8 Attribute ​

基本概念 ​

属性是 PHP 8 引入的一种元数据声明机制,使用 #[Attribute] 语法将结构化数据附加到类、方法、属性、参数等代码元素上。

反射是读取属性的工具,PHP 的反射 API 提供了 getAttributes() 方法来获取声明在代码元素上的属性。

与 DocBlock 注解的区别 ​

特性DocBlock 注解PHP 8 属性
类型安全❌ 字符串,无类型检查✅ 原生 PHP 对象,类型安全
IDE 支持⚠️ 需要插件支持✅ 原生支持,自动补全和跳转
性能⚠️ 需要解析字符串✅ 直接访问,更快
随类继承❌ 不支持❌ 不支持(属性只作用于标注它的类本身)
可重复❌ 手动处理重复✅ 原生支持重复标记(IS_REPEATABLE)
语法高亮❌ 无语法高亮✅ 完整的语法高亮
DocBlock 注解示例(旧方式)
php
<?php
declare(strict_types=1);

class LegacyController
{
    /**
     * @Route("/users", methods={"GET"})
     * @Cache(ttl=3600)
     */
    public function index() {}
}

这种方式存在以下问题:

  • 字符串拼写错误无法被检测
  • IDE 无法提供参数类型提示
  • 需要额外的注解解析库
PHP 8 属性示例(新方式)
php
<?php
declare(strict_types=1);

class PostController
{
    #[GetMapping("/users")]
    #[Cache(ttl: 3600)]
    public function index() {}
}

这种方式的优势:

  • 类型安全,反射读取时即检查
  • IDE 原生支持
  • 无需额外解析库

为什么使用属性系统 ​

1. 类型安全

php
<?php
declare(strict_types=1);

use kuiper\di\attribute\Component;

#[Component]  // ✅ 属性类已导入,反射读取时正常实例化
class UserService {}

// 错误示例
#[Compnent]  // ❌ 属性类不存在,框架反射读取该属性时报错
class UserOrderService {}

2. IDE 支持

php
<?php
declare(strict_types=1);

use kuiper\web\attribute\GetMapping;

class UserController
{
    #[GetMapping(
        mapping: "/users",  // IDE 自动提示参数名(真实参数名是 mapping)
        name: "user_list"   // IDE 显示参数类型
    )]
    public function index(): void {}
}

3. 性能优势

属性由 PHP 引擎原生解析,实例化时直接构造对象,无需像 DocBlock 那样在运行时解析注释字符串,性能更优。

4. 可读性

php
<?php
declare(strict_types=1);

// 属性方式:一目了然
#[Controller]
#[GetMapping("/users")]
class UserController {}

// DocBlock 方式:需要阅读注释
/**
 * @Controller
 * @Route("/users")
 */
class UserOrderController {}

框架提供的属性类型 ​

Kuiper 框架提供了丰富的属性类型,涵盖了依赖注入、Web 路由、中间件等方面。

DI 属性 ​

依赖注入相关的属性用于声明组件和配置。

#[Service] ​

标记类为可被容器管理的业务服务。业务类推荐用它。

php
<?php
use kuiper\di\attribute\Service;

#[Service(description: '用户与订单的业务编排')]
class UserService
{
    // ...
}

参数:

  • value (string, optional): 组件名称,默认为类的完全限定名
  • description (string, optional): 人读描述,目前不参与运行时逻辑, 可供代码生成、文档工具或外部扫描使用

#[Component] ​

标记类为可被容器管理的组件,语义中立。

php
<?php
use kuiper\di\attribute\Component;

#[Component]
class UserOrderCache
{
    // ...
}

参数:

  • value (string, optional): 组件名称,默认为类的完全限定名

#[Service] 继承自 #[Component],两者的依赖注入行为完全等价 (都由组件扫描器识别、注册为容器 bean、默认 Singleton 作用域), 区别只在语义与多出的 description 参数。框架自带组件的注解 (#[Controller]、#[RpcService]、#[RpcClient]、#[HttpClient]、 #[EventListener]、#[Configuration]、#[Command])也都继承自 #[Component]。

#[Configuration] ​

标记类为配置类,可以包含 Bean 定义。

php
<?php
declare(strict_types=1);

use kuiper\di\attribute\Configuration;

#[Configuration]
class AppConfiguration
{
    // ...
}

参数:

  • dependsOn (string[], optional): 依赖的其他配置类

#[Bean] ​

标记配置类中的方法为 Bean 定义方法。

php
<?php
declare(strict_types=1);

use kuiper\di\attribute\Bean;
use kuiper\di\attribute\Configuration;
use PDO;

#[Configuration]
class DatabaseConfiguration
{
    #[Bean]
    public function connection(): PDO
    {
        return new PDO('mysql:host=localhost');
    }
}

参数:

  • name (string, optional): Bean 名称;不写时按规则推导——返回类型非内置类型时用其完全限定名(接口也一样),只有内置类型或没有返回类型时才用方法名

Web 属性 ​

Web 框架相关的属性用于声明路由、控制器和中间件。

#[Controller] ​

标记类为 Web 控制器。

php
<?php
use kuiper\web\attribute\Controller;

#[Controller]  // 继承自 Component
class UserController
{
    // ...
}

路由属性 ​

定义 HTTP 路由,将 URL 映射到控制器方法。路由属性也可标注在类上,作为该控制器所有路由的 URL 前缀。

php
<?php
declare(strict_types=1);

namespace App\controller;

use kuiper\web\attribute\Controller;
use kuiper\web\attribute\DeleteMapping;
use kuiper\web\attribute\GetMapping;
use kuiper\web\attribute\PatchMapping;
use kuiper\web\attribute\PostMapping;
use kuiper\web\attribute\PutMapping;
use kuiper\web\attribute\RequestMapping;
use kuiper\web\controller\AbstractController;
use kuiper\web\controller\ControllerTrait;
use Psr\Http\Message\ResponseInterface;

#[Controller]
class UserController extends AbstractController
{
    use ControllerTrait;

    #[GetMapping("/users")]
    public function index(): ResponseInterface
    {
        return $this->json(['users' => []]);
    }

    #[PostMapping("/users")]
    public function create(): ResponseInterface
    {
        return $this->json(['created' => true]);
    }

    #[PutMapping("/users/{id}")]
    public function update(string $id): ResponseInterface
    {
        return $this->json(['updated' => $id]);
    }

    #[DeleteMapping("/users/{id}")]
    public function delete(string $id): void
    {
        // 返回 null(或声明 : void)时,框架返回控制器自带的响应对象
    }

    #[PatchMapping("/users/{id}")]
    public function patch(string $id): ResponseInterface
    {
        return $this->json(['patched' => $id]);
    }

    #[RequestMapping(
        mapping: "/users/{id}",
        method: ["GET", "POST"]  // 仅 RequestMapping 支持 method 参数
    )]
    public function mixed(string $id): ResponseInterface
    {
        return $this->json(['id' => $id]);
    }
}

参数(真实构造签名,见 web/src/attribute/):

属性签名
RequestMapping__construct(string|array $mapping, string $name = '', array $method = [])
GetMapping / PostMapping / PutMapping / PatchMapping / DeleteMapping / OptionsMapping__construct(string|array $mapping, string $name = '')
  • mapping:URL 路径,字符串或字符串数组(多条路径),支持 {param} 路径参数
  • name:路由名称,供 urlFor() 生成 URL 使用;多条路径时不能设置名称
  • method:HTTP 方法列表,仅 RequestMapping 有此参数

中间件属性 ​

中间件属性可标注在方法或类上,为路由添加 PSR-15 中间件。

php
<?php
declare(strict_types=1);

namespace App\controller;

use kuiper\web\attribute\Controller;
use kuiper\web\attribute\CsrfToken;
use kuiper\web\attribute\DeleteMapping;
use kuiper\web\attribute\GetMapping;
use kuiper\web\attribute\LoginOnly;
use kuiper\web\attribute\PostMapping;
use kuiper\web\attribute\PreAuthorize;
use kuiper\web\attribute\RateLimit;
use kuiper\web\controller\AbstractController;
use kuiper\web\controller\ControllerTrait;
use Psr\Http\Message\ResponseInterface;

#[Controller]
class PaymentController extends AbstractController
{
    use ControllerTrait;

    #[CsrfToken(repeatOk: false)]  // repeatOk 是必填参数
    #[PostMapping("/payment")]
    public function payment(): ResponseInterface
    {
        return $this->json($this->getRequest()->getParsedBody());
    }

    #[LoginOnly]
    #[GetMapping("/dashboard")]
    public function dashboard(): ResponseInterface
    {
        return $this->json(['ok' => true]);
    }

    #[PreAuthorize(requiredAuthorities: ['ADMIN'])]
    #[DeleteMapping("/users/{id}")]
    public function delete(string $id): void
    {
        // ...
    }

    // 限流阈值来自 application.web.rate_limit 配置(window/limit),
    // 属性本身只接受优先级参数
    #[RateLimit(priority: 512)]
    #[GetMapping("/api/data")]
    public function data(): ResponseInterface
    {
        return $this->json([]);
    }
}

真实签名:

属性签名
CsrfToken__construct(bool $repeatOk)(必填)
LoginOnly__construct(int $priority = 101)
RateLimit__construct(int $priority = 512)
PreAuthorize__construct(array $requiredAuthorities, array $anyAuthorities = [])
ErrorHandler__construct(string|array $exceptions)(仅 TARGET_CLASS、不可重复)

错误处理器不是方法级属性

#[ErrorHandler] 只能标注在类上,且同一类只能出现一次,框架没有 on<异常名>() 方法分发约定。 正确用法是写一个可调用类(__invoke() 签名与 Slim\Interfaces\ErrorHandlerInterface 一致):

php
<?php
declare(strict_types=1);

namespace App\handler;

use App\exception\ValidationException;
use kuiper\web\attribute\ErrorHandler;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Throwable;

#[ErrorHandler(ValidationException::class)]
final class ValidationFailedHandler
{
    public function __construct(private readonly ResponseFactoryInterface $responseFactory)
    {
    }

    public function __invoke(
        ServerRequestInterface $request,
        Throwable $exception,
        bool $displayErrorDetails,
        bool $logErrors,
        bool $logErrorDetails
    ): ResponseInterface {
        $response = $this->responseFactory->createResponse(422)
            ->withHeader('Content-Type', 'application/json');
        $response->getBody()->write((string) json_encode([
            'error' => 'validation',
            'message' => $exception->getMessage(),
        ]));

        return $response;
    }
}

如何使用属性 ​

定义和使用 #[Component] ​

php
<?php
declare(strict_types=1);

namespace App\service;

use kuiper\di\attribute\Service;


#[Service]
class EmailService
{
    public function send(string $to, string $subject, string $body): bool
    {
        // 发送邮件逻辑
        return true;
    }
}

定义和使用 #[Configuration] ​

php
<?php
declare(strict_types=1);

namespace App\attributes;

use App\service\EmailService;
use App\service\SmtpEmailService;
use kuiper\di\attribute\Bean;
use kuiper\di\attribute\Configuration;

#[Configuration]
class EmailConfiguration
{
    #[Bean]
    public function emailService(): EmailService
    {
        return new SmtpEmailService(
            host: 'smtp.example.com',
            port: 587,
            username: 'user@example.com',
            password: 'secret'
        );
    }
}

定义和使用 Web 路由属性 ​

php
<?php
declare(strict_types=1);

namespace App\controller;

use App\service\UserService;
use kuiper\web\attribute\Controller;
use kuiper\web\attribute\DeleteMapping;
use kuiper\web\attribute\GetMapping;
use kuiper\web\attribute\PostMapping;
use kuiper\web\attribute\PutMapping;
use kuiper\web\controller\AbstractController;
use kuiper\web\controller\ControllerTrait;
use Psr\Http\Message\ResponseInterface;

#[Controller]
class UserController extends AbstractController
{
    use ControllerTrait;

    public function __construct(
        private UserService $userService
    ) {}

    #[GetMapping("/users")]
    public function index(): ResponseInterface
    {
        return $this->json($this->userService->getAll());
    }

    #[GetMapping("/users/{id}")]
    public function show(string $id): ResponseInterface
    {
        return $this->json($this->userService->find((int) $id));
    }

    #[PostMapping("/users")]
    public function store(): ResponseInterface
    {
        // 框架没有 request() 全局助手,取请求用 $this->getRequest()
        return $this->json($this->userService->create($this->getRequest()->getParsedBody()));
    }

    #[PutMapping("/users/{id}")]
    public function update(string $id): ResponseInterface
    {
        return $this->json($this->userService->update((int) $id, $this->getRequest()->getParsedBody()));
    }

    #[DeleteMapping("/users/{id}")]
    public function destroy(string $id): void
    {
        $this->userService->delete((int) $id);
    }
}

组合使用多个属性 ​

php
<?php
declare(strict_types=1);

namespace App\controller;

use kuiper\web\attribute\Controller;
use kuiper\web\attribute\CsrfToken;
use kuiper\web\attribute\GetMapping;
use kuiper\web\attribute\LoginOnly;
use kuiper\web\attribute\PostMapping;
use kuiper\web\attribute\PreAuthorize;
use kuiper\web\attribute\RateLimit;
use kuiper\web\controller\AbstractController;
use kuiper\web\controller\ControllerTrait;
use Psr\Http\Message\ResponseInterface;

// 中间件属性可同时标注在类和方法上;类上的中间件对该控制器所有路由生效
#[Controller]
#[RateLimit(priority: 512)]
class ApiController extends AbstractController
{
    use ControllerTrait;

    #[LoginOnly]
    #[CsrfToken(repeatOk: false)]
    #[GetMapping("/api/users")]
    public function users(): ResponseInterface
    {
        return $this->json([]);
    }

    #[PreAuthorize(requiredAuthorities: ['ADMIN'])]
    #[RateLimit(priority: 100)]  // 数值越小越先执行,会覆盖类上的 RateLimit
    #[PostMapping("/api/admin/users")]
    public function createUser(): ResponseInterface
    {
        return $this->json([]);
    }
}

自定义属性 ​

定义自定义属性 ​

php
<?php
declare(strict_types=1);

namespace App\attribute;

use Attribute;

#[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_METHOD)]
class Cache
{
    public function __construct(
        public readonly int $ttl = 3600,
        public readonly string $key = ''
    ) {}
}

属性目标:

  • Attribute::TARGET_CLASS: 可用于类
  • Attribute::TARGET_METHOD: 可用于方法
  • Attribute::TARGET_PROPERTY: 可用于属性
  • Attribute::TARGET_PARAMETER: 可用于参数
  • Attribute::TARGET_ALL: 可用于任何目标

可重复标记:

php
#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)]
class Log
{
    public function __construct(
        public readonly string $level,
        public readonly string $message
    ) {}
}

使用自定义属性 ​

php
<?php
declare(strict_types=1);

namespace App\controller;

use App\attribute\Cache;
use kuiper\web\attribute\Controller;
use kuiper\web\attribute\GetMapping;
use kuiper\web\controller\AbstractController;
use kuiper\web\controller\ControllerTrait;
use Psr\Http\Message\ResponseInterface;

#[Controller]
class ProductController extends AbstractController
{
    use ControllerTrait;

    #[Cache(ttl: 600, key: "products")]
    #[GetMapping("/products")]
    public function index(): ResponseInterface
    {
        return $this->json([]);
    }
}

自定义属性需要自己的处理器

框架只会处理它认识的属性。自定义的 #[Cache] 不会自动生效, 需要在配置类或组件中通过反射读取属性并实现相应逻辑。

属性与反射的关系 ​

读取属性 ​

框架通过反射 API 读取属性:

php
<?php
declare(strict_types=1);

use kuiper\web\attribute\Controller;

$reflectionClass = new ReflectionClass(UserController::class);

// 获取所有属性
$attributes = $reflectionClass->getAttributes();

// 获取特定类型的属性
$controllerAttrs = $reflectionClass->getAttributes(Controller::class);

// 获取实例化属性对象
foreach ($controllerAttrs as $attr) {
    $controller = $attr->newInstance();
    // 使用 $controller
}

读取方法属性 ​

php
<?php
declare(strict_types=1);

use kuiper\web\attribute\GetMapping;

$reflectionClass = new ReflectionClass(UserController::class);
$reflectionMethod = $reflectionClass->getMethod('index');

// 获取方法的 GetMapping 属性
$mappingAttrs = $reflectionMethod->getAttributes(GetMapping::class, ReflectionAttribute::IS_INSTANCEOF);

foreach ($mappingAttrs as $attr) {
    /** @var GetMapping $mapping */
    $mapping = $attr->newInstance();
    // GetMapping 的成员是私有的,通过 getter 读取
    echo $mapping->getMapping()[0];  // 输出路由路径
}

高级内容 ​

属性不随类继承 ​

类级属性只作用于标注它的类本身,不会被子类继承。 PHP 的 ReflectionClass::getAttributes() 只返回当前类声明的属性,框架的组件扫描与路由处理也只查看标注类自身:

php
<?php
declare(strict_types=1);

namespace App\controller;

use kuiper\web\attribute\Controller;
use kuiper\web\attribute\RequestMapping;
use kuiper\web\controller\AbstractController;
use kuiper\web\controller\ControllerTrait;

// ❌ 错误期待:父类上的 #[RequestMapping('/base')] 前缀会应用到子类
#[RequestMapping("/base")]
class BaseController extends AbstractController
{
    use ControllerTrait;
}

// BaseController 的路由前缀不会出现在子类上;
// 子控制器需要自己的前缀/中间件/组件属性,必须在子类上各自标注
#[Controller]
#[RequestMapping("/users")]
class UserController extends BaseController
{
}

区分两种情况

  • 类级属性(#[RequestMapping] 前缀、#[Controller]、#[ErrorHandler]、类上的中间件属性等): 不继承,子控制器需各自标注;
  • 方法级属性:跟随方法本身。子类继承到的公有方法仍带着父类里声明的 #[GetMapping] 等方法属性,控制器扫描遍历子类全部方法时同样会注册这些路由。

属性重复 ​

声明为 IS_REPEATABLE 的属性可以在同一目标上多次使用。

php
<?php
declare(strict_types=1);

namespace App\controller;

use Attribute;

#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)]
final class Log
{
    public function __construct(
        public readonly string $level,
        public readonly string $message
    ) {}
}

class ReportController
{
    #[Log(level: "info", message: "Request received")]
    #[Log(level: "debug", message: "Request details")]
    public function index(): void
    {
        // ...
    }
}

属性参数 ​

属性参数可以是标量、数组、类常量,PHP 8.1 起也允许 new 表达式。

php
<?php
declare(strict_types=1);

namespace App\controller;

use App\attribute\Cache;

class ProductController
{
    #[Cache(
        ttl: 600,            // 整数
        key: "products",     // 字符串
    )]
    public function index(): void {}
}

完整示例 ​

下面是一个完整的示例,展示各种属性的实际应用。

php
<?php
declare(strict_types=1);

namespace App\controller;

use App\attribute\Cache;
use App\service\UserService;
use kuiper\web\attribute\Controller;
use kuiper\web\attribute\GetMapping;
use kuiper\web\attribute\LoginOnly;
use kuiper\web\attribute\PostMapping;
use kuiper\web\attribute\RateLimit;
use kuiper\web\controller\AbstractController;
use kuiper\web\controller\ControllerTrait;
use Psr\Http\Message\ResponseInterface;

#[Controller]
#[RateLimit(priority: 512)]
class UserController extends AbstractController
{
    use ControllerTrait;

    public function __construct(
        private UserService $userService
    ) {}

    #[Cache(ttl: 300, key: "users")]  // 自定义属性,需要应用自己实现处理器
    #[GetMapping("/users")]
    public function index(): ResponseInterface
    {
        return $this->json($this->userService->getAll());
    }

    #[LoginOnly]
    #[PostMapping("/users")]
    public function store(): ResponseInterface
    {
        return $this->json($this->userService->create($this->getRequest()->getParsedBody()));
    }

    // 路由参数恒为 string,需要整数时自行转换
    #[Cache(ttl: 600, key: "user_list")]
    #[GetMapping("/users/{id}")]
    public function show(string $id): ResponseInterface
    {
        return $this->json($this->userService->find((int) $id));
    }
}

下一步 ​

了解了属性系统后,您可以:

基于 MIT 许可发布