在/src/AppBundle/Controller/CustomExceptionController.php我有:
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不扩展类Controller。那么如何在这个类中使用$ this-> redirectToRoute?
答案 0 :(得分:3)
redirectToRoute
是您提及的Controller
类的一部分。
您需要做的就是自己创建方法。
首先,您需要将路由器注入CustomExceptionController
(因此您需要将自定义控制器定义为DI中的服务)
services:
my.custom.exception_controller:
class: CustomExceptionController
arguments: [ "@twig", "%kernel.debug%", "@router" ]
twig:
exception_controller: my.custom.exception_controller:showAction
您的自定义类应如下所示:
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,就像在Controller中完成一样(或者直接创建没有辅助方法的RedirectResponse)
/**
* 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);
}
答案 1 :(得分:0)
使用UrlGeneratorInterface(如
)的简便方法// 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' ] );
}
}
getContainer() - 是自己的功能,请参阅手册If you need to generate a URL from a service, type-hint the UrlGeneratorInterface service:
app/assets/fonts