thinkphp8多应用
目录

新建中间件 app/soft/http/middleware/CheckLangMiddleware.php
<?php
declare (strict_types=1);
namespace app\soft\http\middleware;
use think\facade\Request;
use think\facade\Config;
use think\facade\Cookie;
use think\facade\Lang;
class CheckLangMiddleware
{
public function handle($request, \Closure $next)
{
$lang = Request::param('lang') ?? Request::get('lang') ??
Cookie::get('think_lang') ?? Config::get('lang.default_lang');
if (!in_array($lang, Config::get('lang.allow_lang_list'))) {
$lang = Config::get('lang.default_lang');
}
Lang::setLangSet($lang);
if (Request::isGet()) {
Cookie::set('think_lang', $lang, 3600 * 24 * 30);
}
return $next($request);
}
}
新增soft/config/lang.php语言配置文件
<?php
return [
'default_lang' => 'zh-cn', // 默认语言
'allow_lang_list' => ['zh-cn', 'en-us'], // 允许语言列表
'detect_var' => 'lang',
'use_cookie' => true, // 使用Cookie存储语言选择
'cookie_var' => 'think_lang', // Cookie变量名
'extend_list' => [
'zh-cn' => [
app()->getAppPath() . join(DIRECTORY_SEPARATOR, ['lang', 'zh-cn', 'index.php']),
],
'en-us' => [
app()->getAppPath() . join(DIRECTORY_SEPARATOR, ['lang', 'en-us', 'index.php']),
],
]
];
soft/config/route.php修改配置 加入语言中间件
<?php
return [
'middleware' => [
app\soft\http\middleware\CheckLangMiddleware::class,
],
];
新建语言包 soft/lang/zh-cn/index.php
<?php
return [
'index' => '首页',
'product' => '产品列表',
'solution' => '解决方案',
'news' => '新闻资讯',
'aboutus' => '关于我们',
'data' => '数据中心',
];
soft/lang/en-us/index.php
<?php
return [
'index' => 'Index',
'product' => 'Products',
'solution' => 'Solution',
'news' => 'News',
'aboutus' => 'About us',
'data' => 'Data center',
];
前端模板使用
{$Think.lang.index}