Skip to content

最佳实践指南 ​

本文档汇总了使用 Kuiper 框架开发应用时的最佳实践建议,涵盖项目结构、依赖注入、错误处理、性能优化和安全实践等方面。

目录 ​

项目结构最佳实践 ​

目录组织策略 ​

Kuiper 框架支持多种目录组织方式,选择适合你项目规模的组织方式非常重要。

按功能分层(推荐用于中小型项目) ​

src/
├── Controller/          # 控制器层
│   ├── UserController.php
│   └── OrderController.php
├── Service/             # 业务逻辑层
│   ├── UserService.php
│   └── OrderService.php
├── Repository/          # 数据访问层
│   ├── UserRepository.php
│   └── OrderRepository.php
├── Model/               # 数据模型
│   ├── User.php
│   └── Order.php
└── Exception/           # 自定义异常
    └── UserNotFoundException.php

优点:职责清晰,易于理解和维护

缺点:当功能增多时,单个目录可能变得庞大

按模块分组(推荐用于大型项目) ​

src/
├── User/                # 用户模块
│   ├── Controller/
│   ├── Service/
│   ├── Repository/
│   ├── Model/
│   └── Exception/
├── Order/               # 订单模块
│   ├── Controller/
│   ├── Service/
│   └── ...
└── Shared/              # 共享组件
    ├── Logger/
    └── Validator/

优点:高内聚,模块独立,便于团队协作

缺点:可能存在代码重复

混合方式(推荐用于中大型项目) ​

src/
├── Controller/          # 共享控制器基类
├── Service/             # 跨模块业务服务
├── User/                # 用户相关
│   ├── UserController.php
│   ├── UserService.php
│   └── UserRepository.php
└── Order/               # 订单相关
    └── ...

模块划分原则 ​

  1. 单一职责原则:每个模块只负责一个业务领域
  2. 高内聚低耦合:模块内部紧密相关,模块间依赖最小化
  3. 依赖方向:上层依赖下层,Controller → Service → Repository
  4. 共享抽取:多个模块共用的功能抽取到 Shared 目录

命名约定 ​

类命名 ​

  • 控制器:XxxController(如 UserController)
  • 服务:XxxService(如 UserService)
  • 仓库:XxxRepository(如 UserRepository)
  • 模型:业务实体名称(如 User、Order)
  • 异常:XxxException(如 UserNotFoundException)
  • 配置类:XxxConfiguration(如 AppConfiguration)

方法命名 ​

  • 查询方法:get、find、list、search
  • 创建方法:create、add、save
  • 更新方法:update、modify
  • 删除方法:delete、remove
  • 判断方法:is、has、can

变量命名 ​

  • 使用有意义的名称,避免缩写
  • 布尔变量使用 is、has、can 前缀
  • 集合变量使用复数形式
php
// 好
$userList = [];
$isActive = true;

// 差
$users = [];      // 不够具体
$flag = true;     // 含义不明

文件组织建议 ​

  1. 每个类一个文件:保持文件名与类名一致
  2. 使用命名空间:按目录结构组织命名空间
  3. PSR-4 自动加载:确保类路径与命名空间对应
  4. 配置文件集中管理:项目配置在 src/config.php,容器配置在 src/container.php
php
// 命名空间与目录结构对应
namespace App\Service;

class UserService
{
    // 类定义
}

// 文件位置:src/Service/UserService.php

依赖注入最佳实践 ​

组件注解:#[Service] 与 #[Component] ​

需要容器管理的业务类用 #[Service] 标注。两个注解在依赖注入行为上完全等价:

  • kuiper\di\attribute\Service 继承自 kuiper\di\attribute\Component, 只多一个 description 参数(getDescription() 目前框架内没有消费点,属于纯元数据);
  • 两者都由组件扫描器识别并注册为容器 bean,默认单例(容器缓存解析结果)。

为什么业务类用 #[Service]:

  1. 语义明确——#[Service] 直接说明"这是容器管理的业务服务", 读代码时不必再判断这个类为什么被扫描;
  2. 与框架自带组件的注解体系一致——框架的组件注解(#[Controller]、#[RpcService]、 #[RpcClient]、#[HttpClient]、#[EventListener]、#[Configuration]、#[Command]) 都继承自 kuiper\di\attribute\Component,#[Service] 是同一个体系下的应用层写法;
  3. 可以附带描述——#[Service(description: '用户与订单的业务编排')], 描述目前不参与运行时逻辑,但对代码生成、文档工具或外部扫描工具有价值。

#[Component] 保留为语义中立的通用写法,适用于不属于"服务"语义的容器组件, 以及框架自身扩展点。它也是 #[Service] 的父类,两者可以混用。

php
use kuiper\di\attribute\Service;
use kuiper\di\attribute\Component;
// 业务服务:推荐用 #[Service]
#[Service(description: '用户与订单的业务编排')]
class UserService
{
}

// 语义中立的容器组件:用 #[Component]
#[Component]
class UserOrderCache
{
}

构造函数注入优先 ​

推荐做法:通过构造函数注入依赖

php
use kuiper\di\attribute\Service;
use Psr\Log\LoggerInterface;

#[Service]
class UserService
{
    public function __construct(
        private UserRepository $userRepository,
        private LoggerInterface $logger
    ) {
    }

    public function getUser(int $id): User
    {
        $this->logger->info('Getting user', ['id' => $id]);
        return $this->userRepository->find($id);
    }
}

优点:

  • 依赖关系明确
  • 不可变性(依赖在对象生命周期内不变)
  • 易于测试(可以轻松注入 Mock 对象)

不推荐做法:使用 Setter 注入或属性注入

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

// 不推荐
#[Service]
class UserService
{
    #[Inject]  // 属性注入(php-di 的 #[Inject] 需要引入 use DI\Attribute\Inject;)
    private UserRepository $userRepository;

    public function setUserRepository(UserRepository $repo): void
    {
        $this->userRepository = $repo;  // Setter 注入
    }
}

避免循环依赖 ​

循环依赖会导致应用启动失败。

检测方法:

  • 应用启动时会抛出循环依赖异常
  • 查看异常堆栈定位问题

解决方案:

  1. 引入中间服务:将共享依赖抽取到独立服务
php
// 循环依赖示例(两个服务互相注入,容器无法完成构建)
class UserService
{
    public function __construct(private OrderService $orderService) {}
}

class OrderService
{
    public function __construct(private UserService $userService) {}
}
php
// 解决方案:两个服务不再互相依赖,由中间服务编排
class UserService
{
    public function __construct(private UserRepository $userRepository) {}
}

class OrderService
{
    public function __construct(private OrderRepository $orderRepository) {}
}

class UserOrderService  // 新增中间服务
{
    public function __construct(
        private UserService $userService,
        private OrderService $orderService
    ) {}
}
  1. 使用延迟注入:将依赖改为懒加载
php
use kuiper\di\attribute\Service;
use Psr\Container\ContainerInterface;

#[Service]
class UserService
{
    private ?OrderService $orderService = null;

    public function __construct(
        private ContainerInterface $container
    ) {}

    private function getOrderService(): OrderService
    {
        return $this->orderService ??= $this->container->get(OrderService::class);
    }
}

Bean 实例与作用域 ​

Kuiper 的容器基于 php-di,所有 Bean 默认都是单例:$container->get() 第一次解析后会把实例缓存起来, 后续注入和获取都返回同一对象。框架没有 Singleton / Prototype / Request 这类作用域声明, #[Bean] 也不接受除名称以外的参数。

因此:

  • 无状态服务(绝大多数 Service)直接交给容器管理即可;
  • 需要"每次都拿到新对象"的有状态对象,可以注册一个工厂方法 Bean, 或者注入 DI\FactoryInterface 后调用 make()(make() 每次重新构建,不走缓存):
php
use DI\FactoryInterface;
use kuiper\di\attribute\Service;

#[Service]
class UserProfileService
{
    public function __construct(
        private FactoryInterface $factory
    ) {
    }

    public function createBuilder(): UserProfileBuilder
    {
        // make() 每次返回新实例;get() 返回容器缓存的同一个实例
        return $this->factory->make(UserProfileBuilder::class);
    }
}

class UserProfileBuilder
{
    private array $data = [];

    public function addField(string $key, mixed $value): self
    {
        $this->data[$key] = $value;
        return $this;
    }

    public function build(): array
    {
        return $this->data;
    }
}

Bean 命名规范 ​

Bean 名称默认取返回类型类名:#[Bean] 方法有非内建类型的返回值时,Bean 名称就是该返回类型的类名

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

#[Configuration]
class AppConfiguration
{
    #[Bean]  // Bean 名称为 'MyService'(返回类型的类名)
    public function myService(): MyService
    {
        return new MyService();
    }
}

显式指定 Bean 名称:当需要多个相同类型的 Bean 时

php
use DI\Attribute\Inject;
use kuiper\di\attribute\Bean;
use kuiper\di\attribute\Configuration;
use kuiper\di\attribute\Service;

#[Configuration]
class DatabaseConfiguration
{
    #[Bean('primaryDb')]
    public function primaryDatabase(): Connection
    {
        return new Connection('primary');
    }

    #[Bean('replicaDb')]
    public function replicaDatabase(): Connection
    {
        return new Connection('replica');
    }
}

// 使用时通过名称注入(#[Inject] 标注在构造参数上)
#[Service]
class DataRepository
{
    public function __construct(
        #[Inject('primaryDb')]
        private Connection $connection
    ) {}
}

接口类型提示:优先使用接口而非实现类

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
    {
        // 实现
    }
}

#[Service]
class UserService
{
    public function __construct(
        private UserRepositoryInterface $userRepository  // 依赖接口
    ) {}
}

// 差
#[Service]
class UserService
{
    public function __construct(
        private UserRepository $userRepository  // 依赖具体实现
    ) {}
}

错误处理最佳实践 ​

异常层次结构 ​

使用继承建立异常层次:

php
// 基础异常
abstract class AppException extends \Exception
{
}

// 业务异常
abstract class BusinessException extends AppException
{
}

// 各模块异常
class UserNotFoundException extends BusinessException
{
    public function __construct(int $userId)
    {
        parent::__construct("User not found: {$userId}");
    }
}

class InsufficientBalanceException extends BusinessException
{
    public function __construct(float $balance, float $amount)
    {
        parent::__construct(sprintf(
            'Insufficient balance: %.2f, required: %.2f',
            $balance,
            $amount
        ));
    }
}

异常分类:

  • AppException:应用基础异常
  • BusinessException:业务逻辑异常(可预期)
  • SystemException:系统异常(不可预期)
  • ValidationException:验证异常

自定义异常 ​

创建有意义的异常:

php
class OrderCreationException extends BusinessException
{
    public static function outOfStock(int $productId, int $requested, int $available): self
    {
        return new self(sprintf(
            'Product %d out of stock: requested %d, available %d',
            $productId,
            $requested,
            $available
        ));
    }

    public static function invalidStatus(string $currentStatus, string $requiredStatus): self
    {
        return new self(sprintf(
            'Cannot update order: current status is %s, required %s',
            $currentStatus,
            $requiredStatus
        ));
    }
}

// 使用
throw OrderCreationException::outOfStock($productId, $quantity, $available);

包含错误码:便于错误追踪和国际化

php
interface ErrorCodeInterface
{
    public function getErrorCode(): string;
    public function getErrorMessage(): string;
}

class UserException extends BusinessException implements ErrorCodeInterface
{
    private const ERROR_NOT_FOUND = 'USER_NOT_FOUND';
    private const ERROR_INVALID_EMAIL = 'USER_INVALID_EMAIL';

    private ?string $errorCode = null;

    public static function notFound(int $id): self
    {
        $exception = new self("User not found: {$id}");
        $exception->errorCode = self::ERROR_NOT_FOUND;
        return $exception;
    }

    public function getErrorCode(): string
    {
        return $this->errorCode ?? '';
    }

    public function getErrorMessage(): string
    {
        return $this->getMessage();
    }
}

错误日志记录 ​

记录所有异常:在全局异常处理器中记录。#[ErrorHandler] 只能标注在类上, 处理器类必须可调用(__invoke() 签名与 Slim 的 ErrorHandlerInterface 一致)。

两个坑

  1. 用标量而不是数组:属性参数里的 ::class 会被 kuiper\reflection 解析成字面量 字符串("OrderCreationException::class"),因此 #[ErrorHandler([X::class])] 注册不上, 要写 #[ErrorHandler(X::class)];
  2. 按精确异常类名匹配:Slim 不会用父类兜底,标 Throwable 之类的基类永不命中, 应标具体业务异常类。
php
use kuiper\web\attribute\ErrorHandler;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Log\LoggerInterface;
use Throwable;

#[ErrorHandler(OrderCreationException::class)]
class LoggingErrorHandler
{
    public function __construct(
        private readonly ResponseFactoryInterface $responseFactory,
        private readonly LoggerInterface $logger
    ) {
    }

    public function __invoke(
        ServerRequestInterface $request,
        Throwable $e,
        bool $displayErrorDetails,
        bool $logErrors,
        bool $logErrorDetails
    ): ResponseInterface {
        $this->logger->error('Unhandled exception', [
            'exception' => get_class($e),
            'message' => $e->getMessage(),
            'file' => $e->getFile(),
            'line' => $e->getLine(),
            'trace' => $e->getTraceAsString(),
        ]);

        $response = $this->responseFactory->createResponse(500)
            ->withHeader('Content-Type', 'application/json');
        $response->getBody()->write((string) json_encode([
            'error' => 'Internal server error',
        ]));

        return $response;
    }
}

TIP

#[ErrorHandler] 的构造参数是异常类名或类名数组,不是方法上的标记。 没有匹配的处理器时,框架回退到默认的 kuiper\web\handler\ErrorHandler。

记录上下文信息:包含请求相关数据

php
use kuiper\di\attribute\Service;
use Psr\Log\LoggerInterface;

#[Service]
class UserService
{
    public function __construct(
        private LoggerInterface $logger
    ) {
    }

    public function deleteUser(int $userId, int $operatorId): void
    {
        try {
            $this->userRepository->delete($userId);
        } catch (\Exception $e) {
            $this->logger->error('Failed to delete user', [
                'user_id' => $userId,
                'operator_id' => $operatorId,
                'exception' => $e->getMessage(),
            ]);
            throw $e;
        }
    }
}

使用不同日志级别:

  • emergency、alert、critical:系统级别问题
  • error:业务错误,需要关注
  • warning:异常但可恢复
  • notice、info:正常但重要的事件
  • debug:调试信息

用户友好的错误消息 ​

对用户隐藏技术细节:

php
use App\exception\UserNotFoundException;
use kuiper\web\attribute\Controller;
use kuiper\web\attribute\DeleteMapping;
use kuiper\web\controller\AbstractController;
use kuiper\web\controller\ControllerTrait;
use Psr\Http\Message\ResponseInterface;
use Psr\Log\LoggerInterface;

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

    public function __construct(
        private UserService $userService,
        private LoggerInterface $logger
    ) {
    }

    // 路由参数恒为 string,需要整数时自行转换
    #[DeleteMapping('/users/{id}')]
    public function delete(string $id): ResponseInterface
    {
        try {
            $this->userService->deleteUser((int) $id);

            return $this->json(['success' => true]);
        } catch (UserNotFoundException $e) {
            return $this->json([
                'error' => '用户不存在',
            ])->withStatus(404);
        } catch (\Exception $e) {
            $this->logger->error('Delete user failed', ['exception' => $e]);
            return $this->json([
                'error' => '删除用户失败,请稍后重试',
            ])->withStatus(500);
        }
    }
}

提供有用的错误信息:

php
/**
 * 携带字段级错误信息的验证异常。
 */
class ValidationException extends \InvalidArgumentException
{
    /**
     * @param array<string, string> $errors
     */
    public function __construct(
        private readonly array $errors
    ) {
        parent::__construct(implode('; ', $errors));
    }

    /**
     * @return array<string, string>
     */
    public function getErrors(): array
    {
        return $this->errors;
    }
}

// 好:带字段名,便于前端定位
throw new ValidationException(['email' => '邮箱格式不正确']);

// 差:只有一句无上下文的提示
throw new \Exception('Error');

// 更好:一次返回全部字段错误
throw new ValidationException([
    'email' => '邮箱格式不正确',
    'password' => '密码长度至少8位',
]);

性能优化建议 ​

缓存策略 ​

使用多级缓存:L1 内存缓存 → L2 Redis 缓存 → L3 数据库。 框架默认的 PSR-6 缓存池(kuiper\cache\stash\CacheItemPool)已经支持通过 application.cache 配置组合内存 / 文件 / Redis 驱动;需要完全自定义驱动组合时, 覆盖默认 Bean:

php
use kuiper\cache\stash\CacheItemPool;
use kuiper\cache\stash\driver\Composite;
use kuiper\cache\stash\driver\Ephemeral;
use kuiper\cache\stash\driver\RedisDriver;
use kuiper\di\attribute\Bean;
use kuiper\di\attribute\Configuration;
use Psr\Cache\CacheItemPoolInterface;

#[Configuration]
class CacheConfiguration
{
    #[Bean(CacheItemPoolInterface::class)]  // 覆盖框架默认的缓存池 Bean
    public function cache(\Redis $redis): CacheItemPoolInterface
    {
        return new CacheItemPool(new Composite([
            'drivers' => [
                new Ephemeral(['max_items' => 1000]),   // L1: 内存缓存
                new RedisDriver(['redis' => $redis]),  // L2: Redis 缓存
            ],
        ]));
    }
}

TIP

\Redis 连接由框架内置的缓存配置类提供(读取 application.redis 配置, 协程环境下自动套连接池),Bean 方法参数直接按类型注入即可。

缓存热点数据:用户信息、配置信息、字典数据

php
use kuiper\di\attribute\Service;
use Psr\Cache\CacheItemPoolInterface;

#[Service]
class UserService
{
    public function __construct(
        private CacheItemPoolInterface $cache,
        private UserRepository $repository
    ) {
    }

    public function getUser(int $id): User
    {
        $cacheKey = "user:{$id}";
        $item = $this->cache->getItem($cacheKey);

        if ($item->isHit()) {
            return $item->get();
        }

        $user = $this->repository->find($id);
        $item->set($user);
        $item->expiresAfter(3600);  // 1小时
        $this->cache->save($item);

        return $user;
    }
}

缓存预热:应用启动时加载常用数据

php
use kuiper\di\attribute\Bean;
use kuiper\di\attribute\Configuration;
use Psr\Cache\CacheItemPoolInterface;

#[Configuration]
class AppConfiguration
{
    // Bean 方法的参数按类型从容器自动解析
    #[Bean('cacheWarmer')]
    public function cacheWarmer(
        CacheItemPoolInterface $cache,
        UserRepository $userRepository
    ): CacheWarmer {
        return new CacheWarmer($cache, $userRepository);
    }
}

数据库查询优化 ​

使用索引:为常用查询字段添加索引

sql
CREATE INDEX idx_user_email ON users(email);
CREATE INDEX idx_order_status ON orders(status);

避免 N+1 查询:使用预加载或批量查询

php
// 差:N+1 查询
$orders = $orderRepository->findAll();
foreach ($orders as $order) {
    $user = $userRepository->find($order->userId);  // N 次查询
}

// 好:批量查询
$orders = $orderRepository->findAll();
$userIds = array_column($orders, 'userId');
$users = $userRepository->findByIds($userIds);  // 1 次查询
$userMap = array_column($users, null, 'id');
foreach ($orders as $order) {
    $user = $userMap[$order->userId];
}

使用查询构建器:避免原始 SQL

php
// 好:类型安全
$users = $userRepository->findByStatus('active');

// 差:原始 SQL
$users = $db->query("SELECT * FROM users WHERE status = 'active'");

连接池配置 ​

使用连接池:复用数据库、Redis 等长连接。 kuiper\swoole\pool\PoolConfig 的构造函数只接受关联数组(键名支持 snake_case), 不支持命名参数:

php
use kuiper\swoole\pool\DefaultConnectionPool;
use kuiper\swoole\pool\PoolConfig;
use PDO;

// PoolConfig 只接受关联数组,不支持 new PoolConfig(maxConnections: 100) 这种写法
$poolConfig = new PoolConfig([
    'max_connections' => 100,  // 最大连接数
    'min_connections' => 10,   // 最小连接数
    'max_idle_time' => 60,     // 最大空闲时间(秒)
    'wait_timeout' => 5,       // 获取连接的等待超时(秒)
    'aged_timeout' => 300,     // 物理连接最长存活时间(秒),默认 300
]);

$pool = new DefaultConnectionPool(
    'db-pool',
    static fn (int $connId): PDO => new PDO('mysql:host=db;dbname=app', 'user', 'password'),
    $poolConfig
);

$connection = $pool->take();
try {
    $connection->exec('SELECT 1');
} finally {
    $pool->release($connection);
}

TIP

RPC 客户端的连接与超时通过 application.rpc 配置(timeout / connect_timeout 等), 不需要手工组装传输层;连接池主要用在数据库、Redis 等长连接场景。

监控连接池状态:DefaultConnectionPool 实现了 PoolStatisticsInterface, 通过 getStatistics() 一次取回全部指标(框架没有定时任务机制,在请求钩子或监控端点里按需调用即可):

php
use kuiper\di\attribute\Component;
use kuiper\swoole\pool\PoolStatisticsInterface;
use Psr\Log\LoggerInterface;

#[Component]
class ConnectionPoolMonitor
{
    public function __construct(
        private LoggerInterface $logger
    ) {
    }

    // 连接池实例由创建方传入(连接池通常是按需创建的,容器不保证有现成 Bean)
    public function logPoolStats(PoolStatisticsInterface $pool): void
    {
        // 返回键:pool_name / active_connections / idle_connections /
        // total_connections / total_created / total_destroyed /
        // average_wait_time / wait_count / max_connections / min_connections
        $stats = $pool->getStatistics();

        $this->logger->info('Connection pool stats', $stats);

        if ($stats['idle_connections'] < 1 && $stats['active_connections'] >= $stats['max_connections']) {
            $this->logger->warning('Connection pool exhausted', [
                'active' => $stats['active_connections'],
                'max' => $stats['max_connections'],
            ]);
        }
    }
}

协程使用建议 ​

使用 Swoole 协程:提高并发性能。框架没有 Coroutine::batch() 这类封装, 并发调用用 \Swoole\Coroutine::create() + kuiper\swoole\coroutine\Channel 汇聚结果:

php
use kuiper\di\attribute\Service;
use kuiper\swoole\coroutine\Channel;

#[Service]
class DataAggregationService
{
    public function __construct(
        private UserServiceClientInterface $userServiceClient,
        private OrderServiceClientInterface $orderServiceClient
    ) {
    }

    public function aggregateData(int $id): array
    {
        // 并发调用多个服务:每个调用一个协程,结果通过 channel 汇聚
        $channel = new Channel(2);
        \Swoole\Coroutine::create(function () use ($channel, $id): void {
            $channel->push(['user' => $this->userServiceClient->getData($id)]);
        });
        \Swoole\Coroutine::create(function () use ($channel, $id): void {
            $channel->push(['order' => $this->orderServiceClient->getData($id)]);
        });

        return array_merge($channel->pop(), $channel->pop());
    }
}

避免阻塞操作:协程环境不要使用阻塞函数。开启协程 hook(hook_flags)后, \Redis、PDO 等常见扩展调用会被 Swoole 自动切换为协程调度;框架的 Redis Bean 就是通过这种方式支持协程的:

php
use kuiper\cache\RedisFactory;

// 好:框架的 Redis Bean 由 RedisFactory 创建(协程环境自动套连接池),
// 开启 hook_flags 后 I/O 自动协程化
$config = ['host' => '127.0.0.1', 'port' => 6379];
$redis = RedisFactory::createConnection(RedisFactory::buildDsn($config), $config);
$data = $redis->get('key');

// 差:未开启协程 hook 时直接使用阻塞客户端,会卡住整个 worker
$redis = new \Redis();
$redis->connect('127.0.0.1', 6379);  // 阻塞
$data = $redis->get('key');

内存管理 ​

及时释放大对象:

php
use kuiper\di\attribute\Component;
#[Component]
class ReportGenerator
{
    public function generateLargeReport(): string
    {
        $data = $this->loadLargeDataSet();

        try {
            return $this->processData($data);
        } finally {
            unset($data);  // 及时释放
        }
    }
}

使用生成器处理大数据集:

php
use kuiper\di\attribute\Component;

#[Component]
class ReportRepository
{
    // 好:生成器逐条产出,内存占用恒定
    public function processRecords(): iterable
    {
        $offset = 0;
        while (true) {
            $records = $this->findByOffset($offset, 1000);
            if (empty($records)) {
                break;
            }
            foreach ($records as $record) {
                yield $record;
            }
            $offset += 1000;
        }
    }

    // 差:一次性加载全部记录,大数据集可能内存溢出
    public function processAllRecords(): array
    {
        return $this->findAll();
    }
}

安全实践指南 ​

输入验证 ​

验证所有输入:不信任任何用户输入

php
use kuiper\di\attribute\Component;
#[Component]
class UserValidator
{
    public function validateCreateUser(array $data): void
    {
        if (empty($data['email'])) {
            throw new ValidationException('邮箱不能为空');
        }

        if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
            throw new ValidationException('邮箱格式不正确');
        }

        if (strlen($data['password'] ?? '') < 8) {
            throw new ValidationException('密码长度至少8位');
        }
    }
}

使用验证库:如 respect/validation

php
use kuiper\di\attribute\Component;
use Respect\Validation\Validator as v;

#[Component]
class UserValidator
{
    public function validateCreateUser(array $data): void
    {
        $validator = v::key('email', v::email())
            ->key('password', v::length(8))
            ->key('age', v::optional(v::intVal()->min(18)->max(120)));

        if (!$validator->validate($data)) {
            throw new ValidationException('输入验证失败');
        }
    }
}

输出转义 ​

防止 XSS 攻击:输出到 HTML 时转义

twig
{# 好:Twig 自动转义 #}
<p>{{ user.name }}</p>

{# 差:直接输出未转义的变量(如 PHP 模板中) #}
<p><?= $user->name ?></p>

{# 好:手动转义 #}
<p><?= htmlspecialchars($user->name, ENT_QUOTES, 'UTF-8') ?></p>

防止 JSON 注入:使用 JSON 编码

php
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 ApiController extends AbstractController
{
    use ControllerTrait;

    #[GetMapping('/api/users')]
    public function list(): ResponseInterface
    {
        $users = $this->userService->listUsers();

        // 好:json() 走 JSON 编码,Content-Type 自动设置为 application/json
        return $this->json($users);

        // 差:手工拼接 JSON 字符串(容易产生非法 JSON / XSS)
        // echo '{"users":' . json_encode($users) . '}';
    }
}

CSRF 防护 ​

启用 CSRF 令牌:保护状态改变的操作。#[CsrfToken] 的 repeatOk 是必填参数:

php
use kuiper\web\attribute\Controller;
use kuiper\web\attribute\CsrfToken;
use kuiper\web\attribute\PostMapping;
use kuiper\web\controller\AbstractController;
use kuiper\web\controller\ControllerTrait;
use Psr\Http\Message\ResponseInterface;

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

    #[PostMapping('/orders')]
    #[CsrfToken(repeatOk: false)]  // 启用 CSRF 验证,token 不可重复使用
    public function createOrder(): ResponseInterface
    {
        // 表单在请求体中,通过 getRequest() 读取(动作方法不能接收请求对象参数)
        $data = (array) $this->getRequest()->getParsedBody();

        // 处理订单创建(此处省略业务逻辑)
        return $this->json(['created' => true, 'items' => count($data)]);
    }
}

在表单中包含 CSRF 令牌(框架未注册 csrf_token() Twig 函数,token 从控制器传进模板):

php
// 控制器:从请求的 SecurityContext 取 token
use kuiper\web\attribute\Controller;
use kuiper\web\attribute\GetMapping;
use kuiper\web\controller\AbstractController;
use kuiper\web\controller\ControllerTrait;
use kuiper\web\security\SecurityContext;
use Psr\Http\Message\ResponseInterface;

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

    #[GetMapping('/orders')]
    public function create(): ResponseInterface
    {
        $token = SecurityContext::fromRequest($this->getRequest())
            ->getCsrfToken()
            ->getToken();

        return $this->render('order-form.twig', ['csrf_token' => $token]);
    }
}
twig
<!-- 模板中(Twig):把 token 写进隐藏字段 -->
<form method="POST" action="/orders">
    <input type="hidden" name="_csrf_token" value="{{ csrf_token }}">
    <!-- 其他表单字段 -->
</form>

<!-- PHP 模板也可以用内置助手直接生成隐藏字段(name 为 _token) -->
<?= $__helpers::csrfField($csrf_token) ?>

认证授权 ​

使用认证中间件:#[LoginOnly]、#[PreAuthorize] 都是属性中间件; PreAuthorize 的参数是权限数组(requiredAuthorities / anyAuthorities),不是表达式字符串:

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

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

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

    #[PostMapping('/admin/users')]
    #[PreAuthorize(requiredAuthorities: ['ADMIN'])]  // 需要 ADMIN 权限
    public function createUser(): ResponseInterface
    {
        // 请求数据通过 $this->getRequest() 读取
        return $this->json(['created' => true]);
    }
}

TIP

#[PreAuthorize] 依赖容器中的 kuiper\web\security\AclInterface 实现,用于判断当前用户是否拥有指定权限。

实现基于角色的访问控制:

php
use kuiper\di\attribute\Service;
#[Service]
class AuthorizationService
{
    public function hasRole(User $user, string $role): bool
    {
        return in_array($role, $user->getRoles(), true);
    }

    public function hasPermission(User $user, string $permission): bool
    {
        foreach ($user->getRoles() as $role) {
            if ($this->roleHasPermission($role, $permission)) {
                return true;
            }
        }
        return false;
    }
}

敏感数据处理 ​

不在日志中记录敏感信息:

php
use kuiper\di\attribute\Service;
#[Service]
class UserService
{
    public function login(string $email, string $password): User
    {
        $this->logger->info('User login attempt', [
            'email' => $email,
            // 不要记录密码!
        ]);

        // 验证密码
    }
}

加密敏感数据:

php
use kuiper\di\attribute\Service;

#[Service]
class EncryptionService
{
    private string $key;

    public function __construct(
        string $encryptionKey  // 从配置读取
    ) {
        // sodium_crypto_secretbox 要求密钥固定 32 字节(SODIUM_CRYPTO_SECRETBOX_KEYBYTES)
        $this->key = hash('sha256', $encryptionKey, true);
    }

    public function encrypt(string $data): string
    {
        $nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
        $ciphertext = sodium_crypto_secretbox(
            $data,
            $nonce,
            $this->key
        );
        return base64_encode($nonce . $ciphertext);
    }

    public function decrypt(string $encrypted): string
    {
        $data = base64_decode($encrypted);
        $nonce = substr($data, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
        $ciphertext = substr($data, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
        return sodium_crypto_secretbox_open(
            $ciphertext,
            $nonce,
            $this->key
        );
    }
}

使用环境变量存储密钥:配置必须放在 application 键下,env() 来自 kuiper\helper\env:

php
<?php
// src/config.php

declare(strict_types=1);

use function kuiper\helper\env;

return [
    'application' => [
        'security' => [
            'encryption_key' => env('ENCRYPTION_KEY'),
            'jwt_secret' => env('JWT_SECRET'),
        ],
    ],
];

使用 HTTPS:生产环境强制 HTTPS。框架没有 #[Middleware] 属性, 自定义中间件实现 PSR-15 的 MiddlewareInterface 后,注册到 application.web.middleware 配置(值为容器中可解析的类名数组):

php
use kuiper\di\attribute\Component;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

#[Component]  // 注册为容器组件,供 application.web.middleware 按类名解析
class HttpsRedirectMiddleware implements MiddlewareInterface
{
    public function process(
        ServerRequestInterface $request,
        RequestHandlerInterface $handler
    ): ResponseInterface {
        if ($request->getUri()->getScheme() !== 'https' && $this->isProduction()) {
            $uri = $request->getUri()->withScheme('https');
            $response = new \Slim\Psr7\Response(301);

            return $response->withHeader('Location', (string) $uri);
        }

        return $handler->handle($request);
    }

    private function isProduction(): bool
    {
        return (\getenv('APP_ENV') ?: 'dev') === 'prod';
    }
}
php
<?php
// src/config.php:把中间件类名加入 application.web.middleware

return [
    'application' => [
        'web' => [
            'middleware' => [
                App\http\HttpsRedirectMiddleware::class,
            ],
        ],
    ],
];

总结 ​

遵循这些最佳实践可以帮助你:

  1. 构建可维护的项目结构:清晰的代码组织,易于扩展
  2. 编写可测试的代码:通过依赖注入和接口隔离
  3. 提供良好的用户体验:友好的错误处理和快速响应
  4. 保障应用安全:防止常见安全漏洞
  5. 优化应用性能:合理使用缓存、连接池和协程

记住,最佳实践是指导原则,不是绝对规则。根据你的项目需求和团队情况灵活应用。

参考文档 ​

基于 MIT 许可发布