首页 > 解决方案 > Symfony - 如何获取控制器的主要路线?

问题描述

如何获取 Controller 类的路由?就像在这种情况下/book

控制器:

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;


/**
 * @Route("/book")
 */
class BookController extends AbstractController
{

    /**
     * @Route("/")
     */
    public function index() : Response
    {
        return $this->render('book.html.twig');
    }

    /**
     * @Route("/something")
     */
    public function doSomething(){
        // do stuff

        // get the main path/route of this controller; that is '/book', and not '/book/something'

        // do stuff
    }
}

我发现了这个: $path = $this->getParameter('kernel.project_dir')。这并不重要,但我希望有类似的东西。

标签: symfonypathroutescontroller

解决方案


根据您到底想要什么以及您希望它有多灵活,命名路由可能会有所帮助:

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;


/**
 * @Route("/book", name="book")
 */
class BookController extends AbstractController
{
    /**
     * @Route("", name="_index")
     */
    public function index() : Response
    {
        return $this->render('book.html.twig');
    }

    /**
     * @Route("/something", name="_something")
     */
    public function doSomething(){
        // do stuff

        $baseRoute = $this->generateUrl('book_index'); // returns /book

        // do stuff
    }
}

推荐阅读