英文:
Extract path from generateUrl php symfony
问题
我有一个getArticleUrl
方法,返回$this->urlGenerator->generate($article);
在我的函数中,我只需要将查询参数附加到articleUrl
public function articleController(Request $request, string $uuid)
{
$queryParams = $request->query->all();
$articleUrl = $this->getArticleUrl($uuid);
$redirectUrl = 以某种方式附加查询参数;
return new RedirectResponse($redirectUrl, 301);
}
我尝试再次使用生成方法,但它不起作用,因为我认为它已经包含了域名,并且会重复它
$redirectUrl = $this->urlGenerator->generate($articleUrl, $queryParams, UrlGeneratorInterface::ABSOLUTE_URL);
或者也许我可以从$articleUrl
中仅获取路径,并为新路径调用generate
,这可能会起作用,但它没有
public function articleController(Request $request, string $uuid)
{
$queryParams = $request->query->all();
$articleUrl = $this->getArticleUrl($uuid);
$parsed = parse_url($articleUrl);
$path = $parsed['path'];
if ($path) {
$redirectUrl = $this->urlGenerator->generate($path, $queryParams);
} else {
$redirectUrl = $articleUrl;
}
return new RedirectResponse($redirectUrl, 301);
}
英文:
Pretty basic question and I am sorry for that but I haven't find the answer to my problem yet
I have an getArticleUrl
method that returns $this->urlGenerator->generate($article);
In my function, all I need to do is to append the query params to the articleUrl
public function articleController(Request $request, string $uuid)
{
$queryParams = $request->query->all();
$articleUrl = $this->getArticleUrl($uuid);
$redirectUrl = append somehow the query params;
return new RedirectResponse($redirectUrl, 301);
}
I tried to use the generate method again but it didn't work as I supposed it already has the domain in it and it will duplicate it
$redirectUrl = $this->urlGenerator->generate($articleUrl, $queryParams, UrlGeneratorInterface::ABSOLUTE_URL);
or perhaps I could get only the path from $articleUrl
and call the generate
for the new path and that could work, but it didn't
public function articleController(Request $request, string $uuid)
{
$queryParams = $request->query->all();
$articleUrl = $this->getArticleUrl($uuid);
$parsed = parse_url($articleUrl);
$path = $parsed['path'];
if ($path) {
$redirectUrl = $this->urlGenerator->generate($path, $queryParams);
} else {
$redirectUrl = $articleUrl;
}
return new RedirectResponse($redirectUrl, 301);
}
答案1
得分: 1
你可以使用 http_build_query
函数。
更多信息请参考:https://www.php.net/manual/en/function.http-build-query.php
英文:
You could use http_build_query
public function articleController(Request $request, string $uuid)
{
$queryParams = $request->query->all();
$articleUrl = $this->getArticleUrl($uuid);
$redirectUrl = $articleUrl . '?' . http_build_query($queryParams);
return new RedirectResponse($redirectUrl, 301);
}
More Info: https://www.php.net/manual/en/function.http-build-query.php
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论