繁体   English   中英

在 Symfony2 中生成具有特定方案的绝对 URL

[英]Generate absolute URL with specific scheme in Symfony2

我想在 Symfony2 控制器中生成一个具有特定方案 (https) 的绝对 URL。 我找到的所有解决方案都指向我配置目标路由,以便它需要该方案 但是我需要该路由在 http 中保持可访问性,所以我不能将它设置为需要 https(在这种情况下,http 请求被重定向到相应的 https URL)。

有没有办法生成一个 URL,在该 URL 生成的范围内,一个特定的方案?

我看到使用'network'关键字会生成一个“网络路径”样式的 URL,它看起来像“//example.com/dir/file”; 所以也许我可以简单地做

'https:' . $this->generateUrl($routeName, $parameters, 'network')

但我不知道这对于任何路由或请求上下文是否足够健壮。

更新:在对 URL 生成代码进行调查后,这种“网络路径”解决方法似乎完全可靠。 网络路径完全作为绝对 URL 生成,在“//”之前没有方案。

最好的方式去这个

$url = 'https:'.$this->generateUrl($routeName, $parameters, UrlGeneratorInterface::NETWORK_PATH)

根据代码或文档,目前您无法在 generateUrl 方法中执行此操作。 所以你的“hackish”解决方案仍然是最好的,但正如@RaymondNijland评论的那样,你最好使用str_replace

$url = str_replace('http:', 'https:', $this->generateUrl($routeName, $parameters));

如果你想确保它只在字符串的开头改变,你可以写:

$url = preg_replace('/^http:/', 'https:', $this->generateUrl($routeName, $parameters));

不,冒号 ( : ) 在正则表达式中没有特殊含义,因此您不必转义它。

使用默认的UrlGenerator如果您不想弄乱字符串,我认为这是不可能的。

你可以让你自己的HttpsUrlGenerator extends UrlGenerator引入一个细微的变化:

在方法generate() ,而不是:

return $this->doGenerate(
    $compiledRoute->getVariables(), 
    $route->getDefaults(), 
    $route->getRequirements(), 
    $compiledRoute->getTokens(), 
    $parameters, 
    $name, 
    $referenceType, 
    $compiledRoute->getHostTokens(), 
    $route->getSchemes() 
);

你可以这样做:

return $this->doGenerate(
    $compiledRoute->getVariables(), 
    $route->getDefaults(), 
    $route->getRequirements(), 
    $compiledRoute->getTokens(), 
    $parameters, 
    $name, 
    $referenceType, 
    $compiledRoute->getHostTokens(), 
    ['https']
);

如您所见, $route->getSchemes()根据路由设置(您在上面提供的教程链接$route->getSchemes()被注入doGenerate() ) 。

您甚至可以进一步将这个架构数组外部化并通过__construct提供它。

希望这个对你有帮助 ;)

暂无
暂无

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

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