简体   繁体   English

如何扩展UrlGenerator以生成带有斜杠的链接?

[英]How to extend UrlGenerator to generate links with trailing slashes?

I've modified the htaccess file to force the trailing slash and would now like any url generation within Laravel to automatically add the slash so we don't have so many redirects. 我已经修改了htaccess文件以强制使用斜杠,并且现在希望Laravel中的任何url生成都自动添加斜杠,因此我们没有太多重定向。

# Force trailing slash.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*[^/])$ /$1/ [L,R=301]

I then created a CustomUrlGenerator class which extends Illuminate\\Routing\\UrlGenerator and I am trying to override the toRoute function... 然后,我创建了一个CustomUrlGenerator类,该类扩展了Illuminate \\ Routing \\ UrlGenerator,并且尝试覆盖toRoute函数。

protected function toRoute($route, $parameters, $absolute)
{
    $route = parent::toRoute($route, $parameters, $absolute);

    return $route . '/';
}

and in AppServiceProvider.php , I've added the following code... AppServiceProvider.php ,我添加了以下代码...

$this->app->bind('url', function($app) {
    return new CustomUrlGenerator($app['routes']->getBindings(), request());
});

Unfortunately, I think this is breaking the app somehow because whenever I try to use anything which uses this function, it can not find the routes, probably because I'm setting this up too early in the life cycle. 不幸的是,我认为这以某种方式破坏了该应用程序,因为每当我尝试使用任何使用此功能的东西时,它都找不到路由,这可能是因为我在生命周期中设置得太早了。

As per the code in github, toRoute is protected , meaning that you can't override it as public , change your code as follows: 根据github中的代码, toRouteprotected ,这意味着您不能将它重写为public ,如下更改代码:

protected function toRoute($route, $parameters, $absolute)
{
    $route = parent::toRoute($route, $parameters, $absolute);

    return $route . '/';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM