Skip to content

应用生命周期 ​

理解 Kuiper 应用的生命周期对于开发高效、可维护的应用至关重要。本文档详细说明应用从启动到处理请求的完整流程。

生命周期概述

Kuiper 应用的生命周期分为两个主要阶段:

  1. 启动阶段:容器初始化、组件扫描、配置加载
  2. 请求处理阶段:接收请求、路由匹配、中间件执行、控制器调用

应用启动流程 ​

应用启动是指从入口文件加载 vendor/autoload_runtime.php 到容器完全构建完成的过程。 v0.9 起入口不再显式创建应用——Symfony Runtime 体系会自动完成容器构建。

启动流程图 ​

详细启动步骤 ​

1. 入口文件加载 ​

php
<?php
// public/index.php
use Psr\Http\Server\RequestHandlerInterface;

require_once dirname(__DIR__, 1).'/vendor/autoload_runtime.php';

return function (\Psr\Container\ContainerInterface $container) {
    return $container->get(RequestHandlerInterface::class);
};

作用:

  • 加载 Symfony Runtime 的自动加载入口
  • 由 kuiper\runtime\Runtime 接管后续的容器构建
  • 从容器中取出 RequestHandlerInterface 交给 Runtime 驱动

根目录必须有 .env

symfony/runtime 的 bootEnv() 会读取 project_dir/.env,文件缺失直接抛 PathException 导致 500(只有 .env.local 不够)。新项目请至少提交一份 只含非敏感默认值的 .env(或部署流程里 cp .env.example .env)。

2. 配置文件加载 ​

config.php 加载:

php
<?php
// src/config.php
declare(strict_types=1);

use function kuiper\helper\env;

return [
    'application' => [
        // application.env / application.name 由运行时自动注入,这里无需重复声明
        'logging' => [
            'path' => env('LOGGING_PATH', 'logs'),
        ],
    ],
];

container.php 加载:

php
<?php
// src/container.php
declare(strict_types=1);

return [
    'component_scan' => [
        'App\\controller',
        'App\\service',
        'App\\attributes',
    ],
    'configuration' => [
        AppConfiguration::class,
    ],
];

配置文件路径的来源

config.php 与 container.php 的路径不再由入口代码传入,而是由 kuiper\runtime\Runtime 解析,优先级为:

  1. composer.json 的 extra.kuiper.config-file(指向容器配置文件)
  2. 环境变量 APP_CONFIG_FILE(应用配置)、APP_CONTAINER_CONFIG(容器配置)
  3. 缺省值 {basePath}/src/config.php 与 {basePath}/src/container.php

配置类的自动装配

框架与各库包的配置类由自动装配清单接管(kuiper 与库包在 composer.json 的 extra.kuiper.configuration 里声明,运行时从 installed.json 聚合), configuration 里只需列出应用自己的配置类;确需覆盖框架默认时才在这里 显式列出被覆盖的配置类。详见 配置系统。

配置加载顺序

  1. 加载 config.php:应用级配置
  2. 加载 container.php:容器配置
  3. 替换环境变量:处理 env() 调用
  4. 合并默认配置:框架提供的默认值

3. 容器构建过程 ​

关键步骤:

  1. 创建定义源:从配置文件和属性创建定义源
  2. 启用属性扫描:启用 PHP 8 属性支持
  3. 启用自动装配:自动分析构造函数参数
  4. 组件扫描:扫描指定命名空间下的 #[Component] 类
  5. 配置类处理:处理 #[Configuration] 类和 #[Bean] 方法
  6. 构建容器:创建最终的容器实例

4. 组件扫描 ​

php
<?php
// 容器扫描指定命名空间
$namespaces = [
    'App\\controller',
    'App\\service',
    'App\\repository',
];

foreach ($namespaces as $namespace) {
    // 扫描类文件
    $classes = $this->scanNamespace($namespace);

    foreach ($classes as $class) {
        // 检查是否有 #[Component] 属性
        if ($this->hasComponentAttribute($class)) {
            // 注册到容器
            $container->set($class, \DI\autowire($class));
        }
    }
}
组件扫描细节

组件扫描通过以下方式工作:

  1. 使用 Composer 的 ClassLoader 定位类文件
  2. 反射读取类的属性
  3. 检查是否有 #[Component] 或其子属性
  4. 将符合条件的类注册到容器
  5. 解析类的构造函数依赖

5. 配置类处理 ​

php
<?php
#[Configuration]
class AppConfiguration
{
    #[Bean]
    public function databaseConnection(): Connection
    {
        return new Connection(
            host: 'localhost',
            port: 3306
        );
    }

    #[Bean]
    public function userRepository(Connection $connection): UserRepository
    {
        return new DatabaseUserRepository($connection);
    }
}

处理流程:

6. Bean 注册 ​

Bean 是配置类中通过 #[Bean] 方法定义的组件。

php
<?php
declare(strict_types=1);

namespace App\attributes;

use App\service\UserService;
use kuiper\di\attribute\Bean;
use kuiper\di\attribute\Configuration;

#[Configuration]
class UserServiceConfiguration
{
    #[Bean('userService')]  // 自定义名称
    public function userService(): UserService
    {
        return new UserService();
    }
}

Bean 特点:

  • 可以自定义名称
  • 可以访问容器中的其他组件
  • 可以包含复杂的初始化逻辑
  • 按需创建(懒加载)

Bean vs Component

  • Component:简单组件,通过构造函数注入依赖
  • Bean:复杂组件,通过方法参数注入依赖,可以包含初始化逻辑

请求处理流程 ​

请求处理是指从接收 HTTP 请求到返回响应的完整过程。

请求处理流程图 ​

详细请求处理步骤 ​

1. 请求接收(public/index.php) ​

php
<?php
// public/index.php
use Psr\Http\Server\RequestHandlerInterface;

// 加载 Composer 自动加载
require_once dirname(__DIR__, 1).'/vendor/autoload_runtime.php';

// 从容器中获取请求处理器
return function (\Psr\Container\ContainerInterface $container) {
    return $container->get(RequestHandlerInterface::class);
};
入口文件的作用
  • 加载 Symfony Runtime 的自动加载入口
  • 容器由 kuiper\runtime\Runtime 构建,入口无需关心配置文件路径
  • 返回请求处理器
  • 每个请求都会经过这个文件

2. 路由匹配 ​

Slim 框架接收请求后,会进行路由匹配:

php
<?php
declare(strict_types=1);

namespace App\controller;

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

    // 路由参数按位置注入,且恒为 string
    #[GetMapping("/users/{id}")]
    public function show(string $id): ResponseInterface
    {
        // {id} 会被自动解析并注入到 $id 参数;需要整数时自行转换
        return $this->json(['id' => (int) $id]);
    }
}

路由匹配过程:

路由缓存

v0.9 未启用路由缓存:路由表在每次请求时由属性处理器重新扫描并注册 (WebConfiguration 用 AppFactory::createFromContainer() 创建 Slim 应用, 容器中注册的是 Slim\App 本身,未提供自定义的 RouteCollector)。

3. 中间件链执行 ​

中间件在控制器方法前后执行,提供请求预处理和响应后处理。

常见中间件(web/src/middleware/):

  • ErrorMiddleware:错误处理(Slim 提供,框架默认加入)
  • AccessLog:访问日志
  • BodyParsingMiddleware:请求体解析
  • HealthyStatus:健康检查端点
  • Session:会话管理(application.web.session.enabled=true 时自动加入)
  • CsrfToken:CSRF 保护(通过 #[CsrfToken(repeatOk: ...)] 属性启用)

中间件顺序

中间件的执行顺序很重要。默认顺序为:

  1. 错误处理(ErrorMiddleware)
  2. 访问日志(AccessLog)
  3. 请求体解析(BodyParsingMiddleware)
  4. 会话(Session,启用时)
  5. 控制器执行

中间件清单存在容器键 application.web.middleware 中,键值越小越先执行; 可以通过 config.php 的 application.web.middleware 追加全局中间件。

4. 控制器调用 ​

php
<?php
declare(strict_types=1);

namespace App\controller;

use App\service\UserService;
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 UserController extends AbstractController
{
    use ControllerTrait;

    public function __construct(
        private UserService $userService  // 依赖注入
    ) {}

    #[GetMapping("/users/{id}")]
    public function show(string $id): ResponseInterface
    {
        // 1. 路由参数按位置注入,且类型恒为 string
        // 2. 构造函数依赖已由容器注入
        // 3. 取请求统一用 $this->getRequest(),动作方法不能注入 ServerRequestInterface
        $accept = $this->getRequest()->getHeaderLine('Accept');
        $user = $this->userService->find((int) $id);

        // 4. 返回 ResponseInterface(也可以返回 null,框架会使用控制器自带的响应对象)
        return $this->json($user + ['accept' => $accept]);
    }
}

控制器执行流程:

控制器约定

  • 控制器需要 extends AbstractController(并可 use ControllerTrait 获得 json()、getSession() 等辅助方法)
  • 动作方法只接受路由参数(恒为 string,按位置传入),不能声明 ServerRequestInterface 参数
  • 动作方法只能返回 null 或 ResponseInterface,返回其他类型会抛 BadMethodCallException
  • 请求对象用 $this->getRequest() 获取,任意位置也可用 kuiper\web\http\ServerRequestHolder::getRequest()

5. 响应返回 ​

php
<?php
declare(strict_types=1);

namespace App\controller;

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

    #[GetMapping("/users")]
    public function index(): ResponseInterface
    {
        // ControllerTrait::json() 构造 JSON 响应;框架没有 JsonResponse 类
        return $this->json([
            'items' => [
                ['id' => 1, 'name' => 'Alice'],
            ],
        ]);
    }
}

响应处理流程:

关键节点说明 ​

启动阶段关键节点 ​

节点作用输入输出
配置加载加载应用配置配置文件路径配置数组
容器构建创建 DI 容器配置信息容器实例
组件扫描发现组件命名空间组件列表
Bean 注册注册复杂组件配置类Bean 实例

请求处理关键节点 ​

节点作用输入输出
路由匹配匹配 URL 到控制器HTTP 请求路由信息
中间件前置预处理请求HTTP 请求处理后的请求
控制器调用执行业务逻辑路由参数响应对象
中间件后置后处理响应响应对象最终响应

扩展点 ​

Kuiper 应用生命周期提供了多个扩展点,允许开发者插入自定义逻辑。

启动阶段扩展 ​

1. 自定义配置类

php
<?php
declare(strict_types=1);

namespace App\attributes;

use App\service\CustomService;
use kuiper\di\attribute\Bean;
use kuiper\di\attribute\Configuration;

#[Configuration]
class CustomConfiguration
{
    #[Bean]
    public function customService(): CustomService
    {
        // 自定义初始化逻辑
        return new CustomService();
    }
}

2. 全局中间件

自定义 PSR-15 中间件实现 MiddlewareInterface,并在 config.php 的 application.web.middleware 中登记类名:

php
<?php
// src/config.php
declare(strict_types=1);

return [
    'application' => [
        'web' => [
            // 数组前面的先执行;数值键会被 ksort 排序
            'middleware' => [
                \App\middleware\CustomMiddleware::class,
            ],
        ],
    ],
];

注意:通过 #[Component]/#[Bean] 注册到容器只是让中间件可被实例化, 它不会自动进入应用中间件链,仍需在 application.web.middleware 中登记。

请求处理扩展 ​

1. 路由级中间件

框架没有 #[CustomMiddleware] 这种通用属性。路由级中间件需要自定义一个属性类, 继承 kuiper\web\middleware\AbstractMiddlewareFactory(它实现 MiddlewareFactory), 标注 #[Attribute(TARGET_CLASS | TARGET_METHOD)]:

php
<?php
declare(strict_types=1);

namespace App\attribute;

use Attribute;
use kuiper\web\middleware\AbstractMiddlewareFactory;
use Psr\Container\ContainerInterface;
use Psr\Http\Server\MiddlewareInterface;

#[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_METHOD)]
class CustomMiddlewareAttribute extends AbstractMiddlewareFactory
{
    public function create(ContainerInterface $container): MiddlewareInterface
    {
        return $container->get(CustomMiddleware::class);
    }
}

然后标注在控制器类或动作方法上:

php
<?php
declare(strict_types=1);

namespace App\controller;

use App\attribute\CustomMiddlewareAttribute;
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 ProtectedController extends AbstractController
{
    use ControllerTrait;

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

2. 事件监听器

运行时在请求边界分发两个事件(kuiper\runtime\event\):

  • RequestStarted:收到请求、进入应用之前,携带 ServerRequestInterface 与运行模式字符串;
  • RequestFinished:请求处理结束(成功或异常都会分发),携带请求、可空响应、可空异常、耗时与运行模式。

监听器类实现 EventListenerInterface(__invoke(object $event): void 与 getSubscribedEvent(): string),在类上标注 #[EventListener](属性只接受可选的 事件名参数,标在类上):

php
<?php
declare(strict_types=1);

namespace App\listener;

use kuiper\event\attribute\EventListener;
use kuiper\event\EventListenerInterface;
use kuiper\runtime\event\RequestFinished;

#[EventListener(RequestFinished::class)]
class RequestTimingListener implements EventListenerInterface
{
    public function __invoke(object $event): void
    {
        if (!$event instanceof RequestFinished) {
            return;
        }

        // 记录耗时等请求级收尾逻辑
        error_log(sprintf('request finished in %.3fs', $event->getDuration()));
    }

    public function getSubscribedEvent(): string
    {
        return RequestFinished::class;
    }
}

也可以不实现接口,改用 #[EventListener(RequestStarted::class)] 显式指定事件名, 此时只要类可调用(实现 __invoke())即可。

不存在 kernel.request 事件

框架没有 Symfony 风格的 kernel.request 事件,也没有 RequestEvent 类; 请使用上面的 RequestStarted / RequestFinished。

完整示例 ​

下面是一个完整的生命周期示例,展示从启动到请求处理的全过程。

php
<?php
// public/index.php
use Psr\Http\Server\RequestHandlerInterface;

require_once dirname(__DIR__, 1).'/vendor/autoload_runtime.php';

return function (\Psr\Container\ContainerInterface $container) {
    return $container->get(RequestHandlerInterface::class);
};
php
<?php
// demo/src/container.php
declare(strict_types=1);

return [
    'component_scan' => [
        'kuiper\\demo',
    ],
];

框架配置类无需手写

kuiper\web\WebConfiguration 等框架配置类由 extra.kuiper.configuration 自动装配, container.php 通常只需声明应用自身的 component_scan。

php
<?php
// demo/src/config.php
declare(strict_types=1);

use function kuiper\helper\env;

return [
    'application' => [
        // application.env / application.name 由运行时自动注入;这里只覆盖需要自定义的项
        'logging' => [
            'path' => env('LOGGING_PATH', 'logs'),
        ],
    ],
];
php
<?php
// demo/src/IndexController.php
declare(strict_types=1);

namespace kuiper\demo;

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

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

下一步 ​

了解了应用生命周期后,您可以:

基于 MIT 许可发布