feat: 添加前后端多语言支持

前端:
- 在 API 请求中添加 Accept-Language 头,传递当前语言设置

后端:
- 创建 LanguageMiddleware 中间件,自动检测并设置语言
- 为所有 API 路由添加语言中间件

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
root
2026-02-25 18:21:05 +08:00
parent 8817effc9a
commit eef91a6c83
3 changed files with 43 additions and 5 deletions
@@ -0,0 +1,31 @@
<?php
namespace app\middleware;
use support\Translation;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;
class LanguageMiddleware implements MiddlewareInterface
{
public function process(Request $request, callable $next): Response
{
// 从请求头获取语言
$acceptLanguage = $request->header('Accept-Language');
if ($acceptLanguage) {
// 取前两个字符作为语言代码
$locale = substr($acceptLanguage, 0, 2);
// 支持的语言列表
$supportedLocales = ['zh', 'en', 'ru', 'es', 'fr'];
if (in_array($locale, $supportedLocales)) {
Translation::setLocale($locale);
}
}
return $next($request);
}
}