| name | hyperf-codestyle |
|---|---|
| description | Hyperf 3.1 框架编码规范与最佳实践指导。 当需要创建、修改以下文件时激活:Controller、Model、中间件(Middleware)、 注解类、事件监听器、协程调用、配置文件、命令行(Command)。 适用版本:Hyperf 3.1 + Swoole。 |
本 Skill 提供 Hyperf 3.1 框架的标准编码规范,确保 AI 生成的代码符合框架惯例。
核心原则:注解优先,配置次之。 优先使用注解声明式定义行为,仅在注解无法覆盖时才用 config 文件。
app/
├── Controller/ # HTTP 控制器(必须继承 Hyperf\HttpServer\Contract\ResponseInterface)
├── Model/ # ORM 模型(继承 Hyperf\Database\Model\Model)
├── Middleware/ # 中间件
├── Annotation/ # 自定义注解类
├── Listener/ # 事件监听器
├── Process/ # 自定义进程
├── Command/ # 命令行命令
├── Service/ # 业务逻辑层(可选,推荐)
├── Request/ # 请求 DTO(use Hyperf\Validation\Request\FormRequest)
├──Exception/Handler/ # 异常处理器
config/
├── autoload/ # 业务配置(中间件、注解、事件等)
├── container.php # 容器配置
├── dependencies.php # 依赖配置
└── dev.php / prod.php
<?php
declare(strict_types=1);
namespace App\Controller;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\Di\Annotation\Inject;
use App\Service\UserService;
class UserController extends AbstractController
{
#[Inject]
protected UserService $userService;
public function index(ResponseInterface $response)
{
$users = $this->userService->list();
return $response->json([
'code' => 200,
'msg' => 'success',
'data' => $users,
]);
}
}规范:
- 继承
Hyperf\HttpServer\Annotation\Controller+#[AutoController]组合使用,或直接#[AutoController(prefix="/user")] - 路由通过注解声明,无需手动注册
- 禁止在 Controller 中写业务逻辑,委托给 Service 层
- 使用
#[Inject]注入依赖,禁止硬编码make()或ApplicationContext
<?php
declare(strict_types=1);
namespace App\Model;
use Hyperf\Database\Model\Model;
class User extends Model
{
protected ?string $table = 'users';
protected array $fillable = ['name', 'email', 'password'];
protected array $hidden = ['password'];
}规范:
- 必须继承
Hyperf\Database\Model\Model fillable/guarded/hidden/casts必须显式声明- 禁止使用静态全局状态(协程不安全)
<?php
use Hyperf\Di\Annotation\Inject;
use Hyperf\Di\Annotation\ConfigBean;
use Hyperf\Di\Annotation\Value;
class SomeService
{
// 注入服务
#[Inject]
protected OtherService $otherService;
// 注入配置(单个值)
#[Value("key.in.config")]
protected string $configValue;
// 注入配置类(推荐:类型安全)
#[ConfigBean("databases")]
protected array $dbConfig;
}规范:
- 始终用
#[Inject]注入服务,拒绝new实例化 - 配置值用
#[Value]或#[ConfigBean],禁止config()函数散落各处 - 协程上下文用
Hyperf\Context\ApplicationContext::getContainer()->get()获取容器
<?php
declare(strict_types=1);
namespace App\Middleware;
use Hyperf\HttpServer\Router\Handler;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
class CorsMiddleware implements MiddlewareInterface
{
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$response = $handler->handle($request);
return $response
->withHeader('Access-Control-Allow-Origin', '*')
->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
}注册方式(config/autoload/middlewares.php):
<?php
return [
'http' => [
App\Middleware\CorsMiddleware::class,
],
];规范: 中间件通过 config/autoload/middlewares.php 声明式注册,不要硬编码在 Controller 里。
统一响应结构:
return $response->json([
'code' => 200, // 成功用 200,错误自定义错误码
'msg' => 'success',
'data' => $result,
]);错误响应:
return $response->json([
'code' => 400,
'msg' => '参数错误',
'data' => null,
]);不要返回
code: 0、不要返回message字段,统一用msg。
| 文件 | 用途 |
|---|---|
config/autoload/databases.php |
数据库连接配置 |
config/autoload/middlewares.php |
中间件注册 |
config/autoload/annotations.php |
注解扫描路径 |
config/autoload/services.php |
业务服务注册 |
config/container.php |
容器扩展配置 |
config/dependencies.php |
依赖注入配置 |
规范:
- 业务配置放
config/autoload/,不要修改config.php - 配置用
config()函数读取,类型安全场景用#[ConfigBean]
| 注解 | 场景 |
|---|---|
#[AutoController] |
自动路由(Controller) |
#[Controller] |
手动路由分组 |
#[RequestMapping] |
HTTP 方法+路由 |
#[Get] #[Post] #[Put] #[Delete] |
REST 方法 |
#[Inject] |
依赖注入 |
#[Value] |
注入单个配置值 |
#[ConfigBean] |
注入配置类 |
#[Aspect] |
AOP 切面 |
#[EventListener] |
事件监听 |
#[Command] |
命令行命令 |
当注解无法实现时(复杂配置、动态行为),才使用 config 文件或手动注册。
<?php
use Hyperf\Context\ApplicationContext;
// ❌ 错误:全局变量/静态变量在协程间共享
class BadService
{
public static array $cache = []; // 禁止
}
// ✅ 正确:使用 Context 存储协程隔离数据
use Hyperf\Context\Context;
Context::set('key', $value);
$value = Context::get('key');详细规范请阅读以下文件:
- 项目结构详解: references/project-structure.md
- 注解速查表: references/annotations.md
- 配置文件示例: references/config-files.md