Symfony 3中的Catch-all路线

64jmpszr  于 12个月前  发布在  其他
关注(0)|答案(3)|浏览(101)

我在Symfony2中有一个全面的回退路由,我不能在Symfony3中工作。我尝试了这个确切的语法(我的Symfony2路由的逐字副本),但没有工作。

fallback:
    path:     /{req}
    defaults: { _controller: MyBundle:Default:catchAll }
    requirements:
        req: ".+"

我怎样才能让它在Symfony3中工作呢?(这是我使用Symfony3和保持在v2.8的唯一障碍)

vc9ivgsu

vc9ivgsu1#

这将帮助您:

route1:
  path: /{req}
  defaults: { _controller: 'AppBundle:Default:index' }
  requirements:
      req: ".+"

其中,我的控制器名为“DefaultController”,我有一个函数名为“indexAction()"。
下面是我的DefaultController代码:

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request)
...

我确实在我的环境中尝试了你所说的,直到我指定了正确的控制器设置才起作用。
编辑:
要做到这一点,需要将参数Request $requestwith the type hint)添加到操作的方法签名中。

8zzbczxx

8zzbczxx2#

我发现目前接受的答案 * 几乎 * 对Symfony 4有用,所以我要添加我的解决方案:
这就是我在Symfony 4中所做的工作:

  • 打开/src/Controller/DefaultController.php,确保有一个名为index(){}的函数
  • 这是 * 不 * 需要添加Request $request作为第一个参数,因为一些评论建议。
  • 这个方法将处理routes.yaml捕获的所有url
  • 打开/config/routes.yaml,添加以下内容:
yourRouteNameHere:
    path: /{req}
    defaults: { _controller: 'App\Controller\DefaultController::index' }
    requirements: #            the controller --^     the method --^
      req: ".*"`  # not ".+"
gxwragnw

gxwragnw3#

您还可以覆盖异常控制器。

# app/config/config.yml
twig:
    exception_controller:  app.exception_controller:showAction

# app/config/services.yml
services:
    app.exception_controller:
        class: AppBundle\Controller\ExceptionController
        arguments: ['@twig', '%kernel.debug%']
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 ExceptionController
{
    protected $twig;

    protected $debug;

    public function __construct(\Twig_Environment $twig, $debug)
    {
        $this->twig = $twig;
        $this->debug = $debug;
    }

    public function showAction(Request $request, FlattenException $exception, DebugLoggerInterface $logger = null)
    {
        // some action

        return new Response($this->twig->render('error/template.html.twig', [
                'status_code' => $exception->getStatusCode()
            ]
        ));
    }
}

相关问题