我使用LaravelGettext
包在Laravel中编写了一个本地化中间件,如下所示:
<?php
namespace App\Http\Middleware;
use Closure;
class Locale {
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next) {
if ($request->method() === 'GET') {
$segment = $request->segment(1);
if (!in_array($segment, config('laravel-gettext.supported-locales'))) {
$segments = $request->segments();
$fallback = session('locale') ?: config('laravel-gettext.fallback-locale');
$segments = array_prepend($segments, $fallback);
return redirect()->to(implode('/', $segments));
}
session(['locale' => $segment]);
LaravelGettext::setLocale($segment);
}
return $next($request);
}
}
我通过以下方式路由到中间件
Route::prefix('{lang?}')->middleware('locale')->group(function () {
...
}
尽管在中间件上运行却给了我这个错误:
"Class 'App\Http\Middleware\LaravelGettext' not found"
所以我认为我可能必须通过添加以下内容来手动导入LaravelGettext
软件包:
use Xinax\LaravelGettext\LaravelGettext;
现在给我这个例外:
"Non-static method Xinax\LaravelGettext\LaravelGettext::setLocale() should not be called statically"
这让我想知道:甚至没有有效的选项来访问中间件中的软件包?还是我在这里遇到了设计缺陷?
答案 0 :(得分:0)
好吧,我只是不得不导入Facade,而不是实际的类本身。因此添加
use Xinax\LaravelGettext\Facades\LaravelGettext;
终于成功了!