Php 在CustomExceptionController中访问redirectToRoute
在/src/AppBundle/Controller/CustomExceptionController.php中,我有:Php 在CustomExceptionController中访问redirectToRoute,php,symfony,Php,Symfony,在/src/AppBundle/Controller/CustomExceptionController.php中,我有: namespace AppBundle\Controller; use Symfony\Component\Debug\Exception\FlattenException; use Symfony\Component\HttpKernel\Log\DebugLoggerInterface; use Symfony\Component\HttpFoundation\Req
namespace AppBundle\Controller;
use Symfony\Component\Debug\Exception\FlattenException;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class CustomExceptionController extends \Symfony\Bundle\TwigBundle\Controller\ExceptionController
{
public function showAction(Request $request, FlattenException $exception, DebugLoggerInterface $logger = null)
{
return $this->redirectToRoute('custom_error'); //not working
}
}
这不起作用,因为\Symfony\Bundle\TwigBundle\Controller\ExceptionController未扩展类控制器。那么,我如何在这个类中使用$this->redirectToRoute呢?
redirectToRoute
就像您提到的那样是控制器
类的一部分。
您所需要做的就是自己创建方法
首先,您需要将路由器注入CustomExceptionController
(因此您需要将自定义控制器定义为DI中的服务)
您的自定义类应如下所示:
class CustomExceptionController extends \Symfony\Bundle\TwigBundle\Controller\ExceptionController
{
protected $router;
public function __construct(\Twig_Environment $twig, $debug, Router $router)
{
parent::__construct($twig, $debug);
$this->router = $router;
}
public function showAction(Request $request, FlattenException $exception, DebugLoggerInterface $logger = null)
{
}
}
之后,您可以像在控制器中一样在CustomExceptionController中实现redirectToRoute(或者直接创建RedirectResponse而不使用helper方法)
使用UrlGeneratorInterface-like的简单方法
getContainer()->get('router')->generate( 'custom_error', ['key' => 'some val'], 0 );
getContainer()-是自己的函数,请参阅手册
/**
* Returns a RedirectResponse to the given URL.
*
* @param string $url The URL to redirect to
* @param int $status The status code to use for the Response
*
* @return RedirectResponse
*/
public function redirect($url, $status = 302)
{
return new RedirectResponse($url, $status);
}
/**
* Returns a RedirectResponse to the given route with the given parameters.
*
* @param string $route The name of the route
* @param array $parameters An array of parameters
* @param int $status The status code to use for the Response
*
* @return RedirectResponse
*/
protected function redirectToRoute($route, array $parameters = array(), $status = 302)
{
return $this->redirect($this->router->generateUrl($route, $parameters), $status);
}
getContainer()->get('router')->generate( 'custom_error', ['key' => 'some val'], 0 );
// src/Service/SomeService.php
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class SomeService
{
private $router;
public function __construct(UrlGeneratorInterface $router)
{
$this->router = $router;
}
public function someMethod()
{
$url = $this->router->generate( 'custom_error', [ 'key' => 'some value' ] );
}
}