PHP高性能API开发实战:从RESTful到JWT鉴权全解析
一、现代API设计核心原则
PHP 8.1+为API开发提供了强大的新特性:
// 使用枚举定义状态码
enum StatusCode: int {
case SUCCESS = 200;
case BAD_REQUEST = 400;
case UNAUTHORIZED = 401;
}
// 强类型返回值声明
function getUser(int $id): array|false {
$data = DB::query("SELECT * FROM users WHERE id = ?", [$id]);
return $data ?: false;
}
五大设计原则:无状态、资源导向、版本控制、文档完善、安全防护
二、高性能路由实现方案
1. 快速路由解析
// 使用FastRoute实现高性能路由
$dispatcher = FastRoutesimpleDispatcher(function(FastRouteRouteCollector $r) {
$r->addRoute('GET', '/users/{id:d+}', 'UserController@show');
$r->addRoute('POST', '/users', 'UserController@store');
});
// 请求处理
$httpMethod = $_SERVER['REQUEST_METHOD'];
$uri = $_SERVER['REQUEST_URI'];
$routeInfo = $dispatcher->dispatch($httpMethod, $uri);
2. 自动路由缓存
// 生产环境启用路由缓存
if ($env === 'prod') {
$dispatcher = FastRoutecachedDispatcher($routeDefinitionCallback, [
'cacheFile' => __DIR__ . '/route.cache',
'cacheDisabled' => false,
]);
}
三、JWT鉴权深度实践
1. 安全的Token生成
use FirebaseJWTJWT;
function generateJWT(array $user): string {
$payload = [
'iss' => 'your-domain.com',
'aud' => 'your-app',
'iat' => time(),
'exp' => time() + 3600,
'uid' => $user['id'],
'role' => $user['role']
];
return JWT::encode(
$payload,
getenv('JWT_SECRET'),
'HS256'
);
}
2. 中间件验证实现
class AuthMiddleware {
public function handle(Request $request, Closure $next) {
try {
$token = $request->getHeader('Authorization')[0] ?? '';
$decoded = JWT::decode(
str_replace('Bearer ', '', $token),
getenv('JWT_SECRET'),
['HS256']
);
$request->user = $decoded;
return $next($request);
} catch (Exception $e) {
return response(['error' => '未授权'], 401);
}
}
}
四、性能优化关键指标
优化措施 | 请求/秒(QPS) | 内存占用 |
---|---|---|
基础实现 | 320 | 45MB |
850 | 32MB | |
OPcache+JIT | 1200 | 28MB |
测试环境:PHP 8.2 / 4核CPU / 8GB内存
五、电商API实战案例
1. 商品搜索接口
// 使用预处理语句防止SQL注入
$search = $request->get('q');
$page = max(1, (int)$request->get('page', 1));
$perPage = 15;
$stmt = DB::prepare("
SELECT id, name, price
FROM products
WHERE name LIKE ?
AND status = 1
LIMIT ? OFFSET ?
");
$stmt->execute(["%$search%", $perPage, ($page-1)*$perPage]);
return [
'data' => $stmt->fetchAll(),
'meta' => [
'page' => $page,
'per_page' => $perPage
]
];
六、安全防护最佳实践
- 输入验证:使用filter_var过滤所有输入
- CSRF防护:表单令牌验证
- 速率限制:Redis实现接口限流
- 敏感数据:密码使用password_hash存储
- HTTPS:强制所有通信加密