Laravel 5.0.*中间件在处理路由之前从URL删除前缀语言环境 [英] Laravel 5.0.* middleware to remove prefix locale from url before routes are processed

查看:27
本文介绍了Laravel 5.0.*中间件在处理路由之前从URL删除前缀语言环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种使所有应用程序路由都具有多个语言环境而不使用路由组的方法.这是因为我使用了一个外部扩展程序包,这意味着路由在许多地方都已注册.

I am looking for a way to make all app route's have multiple locales without using route groups. This is because I use an external extensions package, which means routes are registered in many places.

基本上,我希望/foot/bar路线能够识别和处理/foo/bar以及/en/foo/bar,/de/foor/bar,/es/foo/bar等所有内容

Essentially I want to have /foo/bar as well as /en/foo/bar, /de/foor/bar, /es/foo/bar etc all to be recognised and processed by the /foot/bar route

 Route::get('foo/bar', function () {
     return App::getLocale() . ' result';
 });

因此,以上内容会给我结果"或结果"或结果".

So the above would give me 'en result' or 'de result' or 'es result'.

我已经有了基于路径段设置语言环境的中间件.我没有运气就尝试了以下方法.

I already have middleware that sets the locale based on the path segment. I have tried the following with no luck.

   ...
   $newPath =  str_replace($locale,'',$request->path());

   $request->server->set('REQUEST_URI',$new_path);

 }

 return $next($request);

希望这是可能的,或者有其他实现方法.

Hopefully this is possible, or there is some other way of achieving it.

编辑------

基于下面的评论,我通过将以下代码添加到public/index.php中来对其进行了快速修改.希望这样可以更好地了解我要通过编辑请求对象来实现的目标.

Based on a comment below I quickly hacked it by adding the following code into public/index.php. Hopefully this will give a better idea of what i'm trying to achieve by editing the request object.

$application_url_segments = explode( '/', trim( $_SERVER["REQUEST_URI"], '/' ) );

$application_locale = $application_url_segments[0];

$application_locales = ['en' => 'English', 'de' => 'German'];

if ( array_key_exists( $application_locale, $application_locales ) ) {

    $_SERVER["REQUEST_URI"] = str_replace( '/' . $application_locale,'',$_SERVER["REQUEST_URI"] );

}

推荐答案

以下是在调用路由之前编辑URL的正确代码.

Here is the correct code to edit the URL before the routes get called.

<?php namespace App\Providers;
use Illuminate\Foundation\Application;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Request;

class LanguageServiceProvider extends ServiceProvider {
    public function register() {
      Request::instance()->server->set('REQUEST_URI',"/uri/");
    }
}

请注意,从Request实例获取路径而不先复制它,由于某种原因,这将导致REQUEST_URI不可编辑.我假设在代码库中的某个地方,laravel在调用path()方法时正在初始化请求.

To note, fetching the path from the Request instance without duplicating it first will for some reason cause the REQUEST_URI to not be editable. I assume somewhere in the codebase laravel is initializing the request when you call the path() method.

这篇关于Laravel 5.0.*中间件在处理路由之前从URL删除前缀语言环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆