没有自定义控制器的 Symfony 4 重定向
Symfony 4 Redirect without a custom controller
所以我面临的问题是,我无法在 routing.yml
中配置的重定向中使用通配符
homepage:
path: /test/{wildcard}
controller: Symfony\Bundle\FrameworkBundle\Controller\RedirectController::urlRedirectAction
defaults:
path: /{wildcard}
permanent: true
在默认路径中我需要获取通配符路径。因此,例如 test/wildcard 应该重定向到 /wildcard。
但是 Symfony 正在做的是,它重定向到 /{wildcard}。
那么如何获取通配符参数呢?
所以为了回答我的问题。
解决方案如下:
您需要创建一个自定义 RedirectController
,它能够处理
路由中的通配符。
控制器的外观如下:
<?php
namespace Custom\RedirectBundle\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
class RedirectController
{
public function urlRedirectAction(
Request $request,
bool $permanent = false,
string $route = '',
array $dynamicRoutePath =
[]
): RedirectResponse {
$statusCode = $permanent ? 301 : 302;
if ('' !== $route) {
$url = "/".$route;
if (!empty($dynamicRoutePath)) {
$url = $this->getPath($request, $dynamicRoutePath, $url);
}
return new RedirectResponse($url, $statusCode);
}
$route = $this->getPath($request, $dynamicRoutePath);
return new RedirectResponse($route, $statusCode);
}
private function getPath(Request $request, array $path, string $url = ''): string
{
foreach ($path as $pathParameter) {
$pathconfig = $request->get($pathParameter);
$url = $url."/".$pathconfig;
}
return $url;
}
}
routing.yml中的配置:
magazin_category_slug:
path: /magazin/{category}/{slug}
controller: CustomRedirectBundle:Redirect:urlRedirect
defaults:
permanent: true
route: newBaseRoute
dynamicRoutePath:
- category
所以我面临的问题是,我无法在 routing.yml
中配置的重定向中使用通配符homepage:
path: /test/{wildcard}
controller: Symfony\Bundle\FrameworkBundle\Controller\RedirectController::urlRedirectAction
defaults:
path: /{wildcard}
permanent: true
在默认路径中我需要获取通配符路径。因此,例如 test/wildcard 应该重定向到 /wildcard。 但是 Symfony 正在做的是,它重定向到 /{wildcard}。 那么如何获取通配符参数呢?
所以为了回答我的问题。
解决方案如下:
您需要创建一个自定义 RedirectController
,它能够处理
路由中的通配符。
控制器的外观如下:
<?php
namespace Custom\RedirectBundle\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
class RedirectController
{
public function urlRedirectAction(
Request $request,
bool $permanent = false,
string $route = '',
array $dynamicRoutePath =
[]
): RedirectResponse {
$statusCode = $permanent ? 301 : 302;
if ('' !== $route) {
$url = "/".$route;
if (!empty($dynamicRoutePath)) {
$url = $this->getPath($request, $dynamicRoutePath, $url);
}
return new RedirectResponse($url, $statusCode);
}
$route = $this->getPath($request, $dynamicRoutePath);
return new RedirectResponse($route, $statusCode);
}
private function getPath(Request $request, array $path, string $url = ''): string
{
foreach ($path as $pathParameter) {
$pathconfig = $request->get($pathParameter);
$url = $url."/".$pathconfig;
}
return $url;
}
}
routing.yml中的配置:
magazin_category_slug:
path: /magazin/{category}/{slug}
controller: CustomRedirectBundle:Redirect:urlRedirect
defaults:
permanent: true
route: newBaseRoute
dynamicRoutePath:
- category