kingcode / laravel-localize
快速实现 Laravel 本地化。
v2.2
2020-11-08 13:17 UTC
Requires
- php: ^7.3|^8.0
- laravel/framework: ^6.0|^7.0|^8.0
Requires (Dev)
- mockery/mockery: ^1.4.2
- orchestra/testbench: ^6.0
- phpunit/phpunit: ^9.3.3
README
尽可能简约的本地化包,使得在 /nl/home
路径下,app.locale
设置为 nl
。
安装
要求安装此包。
composer require kingscode/laravel-localize
... 可选地发布配置文件。
php artisan vendor:publish --provider="KingsCode\LaravelLocalize\LocalizeServiceProvider"
将中间件添加到所需的中介组中,在我们的例子中只添加到 web 组。
<?php namespace App\Http; class Kernel extends HttpKernel { ... /** * The application's route middleware groups. * * @var array */ protected $middlewareGroups = [ 'web' => [ ... LocaleSelector::class, // <<<<<< Here it is. SubstituteBindings::class, // Its best to register before substitute bindings. ... ], ]; ... }
现在您必须注册包含您本地化路由的路由文件,您将这样做两次
- 一次不带前缀,一次带前缀。
- 一次带前缀,一次不带前缀。
这使得默认语言可以仅使用 /
,而不是默认英语网站强制使用 /en
。
<?php use Illuminate\Contracts\Config\Repository; use Illuminate\Routing\Router; use KingsCode\LaravelLocalize\Localize; class RouteServiceProvider extends ServiceProvider { public function map() { // Web routes without localization, like a "/file/{file}" route or such. $this->mapWebRoutes(); // And as the last method call you'll do the localized web routes. $this->mapLocalizedWebRoutes(); } /** * Define the localized "web" routes for the application. * * @return void */ protected function mapLocalizedWebRoutes() { // We'll take stuff from the config to keep things easily configurable. // Not a must, but it prevents you from having to override stuff. $config = $this->app->make(Repository::class); // We'll need a router to register routes duh. $router = $this->app->make(Router::class); /** @var Localize $localize */ $localize = $this->app->make(Localize::class); // Okay so here is an IMPORTANT part. // Register the {locale} routes first otherwise {locale}/{any} will not be reachable and {any} will catch everything. $router->middleware('web') ->namespace($this->namespace) ->prefix('{' . $config->get('localize.route_parameter_key') . '}') // We add the prefix. ->where([$config->get('localize.route_parameter_key') => $localize->getRouteRegex()]) ->name($config->get('localize.route_name_prefix') . '.') // And the name prefix. ->group(base_path('routes/localized.web.php')); $router->middleware('web') ->namespace($this->namespace) ->group(base_path('routes/localized.web.php')); } }