Laravel 使用注释的路由-传递自定义变量和转换

Laravel 使用注释的路由-传递自定义变量和转换,laravel,annotations,laravel-routing,laravel-5,laravel-annotations,Laravel,Annotations,Laravel Routing,Laravel 5,Laravel Annotations,使用routes.php,使用前缀为不同语言创建路径非常容易,例如,我们可以使用以下方法为about页面创建about路由about和pl/o-nas URL到同一路由: if (\Request::segment(1) =='pl') { $prefix ='pl'; \App::setLocale('pl'); } else{ $prefix =''; \App::setLocale('en'); } Route::group( array('pre

使用routes.php,使用前缀为不同语言创建路径非常容易,例如,我们可以使用以下方法为about页面创建about路由about和pl/o-nas URL到同一路由:

if (\Request::segment(1) =='pl') {
    $prefix ='pl';
    \App::setLocale('pl');
}
else{
    $prefix ='';
    \App::setLocale('en');
}

Route::group(
    array('prefix' => $prefix,
    function () {
        Route::any('/'.trans('routes.about'), 'Controller@action'); 
    }
);
但正如我们所知,默认情况下,Laravel5使用注释。使用注释是否可以实现同样的效果?目前,关于在Laravel5中使用注释的信息并不多

您可以先将类似代码添加到RouteServiceProver方法中:

if (\Request::segment(1) =='en') {
    $routePrefix ='';
    $this->app->setLocale('en');
}
else{
    $routePrefix ='pl';
    $this->app->setLocale('pl');
}
但是我们如何在注释本身中使用前缀和翻译,以及如何在这里使用trans函数呢?它应该是这样的,但显然不起作用,因为您不能简单地将函数放入注释中,我不知道是否有任何方法可以在这里添加前缀

/**
 * @Get("/trans('routes.about')")
 * @prefix: {$prefix}
 */
public function about()
{
   return "about page";
}

像这样的方法应该会奏效:

<?php namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Routing\Middleware;

class LangDetection implements Middleware {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->segment(1) =='en') {
              $this->app->setLocale('en');
        }
        else{
              $this->app->setLocale('pl');
        }

        return $next($request);
    }

}

编辑:或者,您不必将其放入堆栈中,您可以将其作为“中间件过滤器”保留,只需在特定路由上调用它-与您对“auth”、“csrf”等的操作相同

您是否可以使用中间件,解析任何语言要求的路由-并在中间件中设置它,在它到达您的控制器之前?@Shift Exchange可能我可以,但目前我不知道如何执行此操作问题是,此中间件还应修改请求,从url中删除前缀,并翻译路由,以便立即转到正确的控制器如果我有url“pl/o-nas”,此中间件将正确设置语言,但仍将查找pl/o-nas注释,而不是关于您可以在您的中间件中创建一个新的$request对象,而不使用前缀,然后将其传递给$next$request。如果中间件在您的主堆栈中运行,它会在确定运行哪个路由之前发生,因此它会选择正确的控制器。请演示如何根据当前URL轻松更改$request URL/创建新的请求对象?我以前没做过,也不知道怎么做。我不知道我是应该创建新请求还是克隆当前请求,并以某种方式编辑url,以确保请求也包含方法POST/GET/和其他必要的数据。
protected $stack = [
    'App\Http\Middleware\LangDetection',
    'Illuminate\Cookie\Middleware\Guard',
    'Illuminate\Cookie\Middleware\Queue',
    'Illuminate\Session\Middleware\Reader',
    'Illuminate\Session\Middleware\Writer',
];