在/src/AppBundle/Controller/CustomExceptionController.php 我有:
namespace AppBundleController;
use SymfonyComponentDebugExceptionFlattenException;
use SymfonyComponentHttpKernelLogDebugLoggerInterface;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
class CustomExceptionController extends SymfonyBundleTwigBundleControllerExceptionController
{
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
是你提到的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 SymfonyBundleTwigBundleControllerExceptionController
{
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 而无需使用帮助程序方法(
/**
* 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);
}
使用UrlGeneratorInterface的简单方法,例如
getContainer()->get('router')->generate( 'custom_error', ['key' => 'some val'], 0 );
getContainer(( - 是自己的功能,请参阅手册 如果需要从服务生成 URL,请键入提示 UrlGeneratorInterface 服务:
// src/Service/SomeService.php
use SymfonyComponentRoutingGeneratorUrlGeneratorInterface;
class SomeService
{
private $router;
public function __construct(UrlGeneratorInterface $router)
{
$this->router = $router;
}
public function someMethod()
{
$url = $this->router->generate( 'custom_error', [ 'key' => 'some value' ] );
}
}