【问题标题】:Symfony - How to get the main route of the controller?Symfony - 如何获取控制器的主要路线?
【发布时间】:2021-06-06 08:45:21
【问题描述】:

如何只获取 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-&gt;getParameter('kernel.project_dir')。这并不重要,但我希望有类似的东西。

【问题讨论】:

  • 那种东西都是编译和缓存的,所以我不认为 /book 本身存储在某个地方。也许您可以解释为什么需要它,并且可以建议一种替代方法。否则,只需将其存储为类常量。

标签: symfony path routes controller


【解决方案1】:

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

<?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
    }
}

【讨论】:

    【解决方案2】:

    我找到了一个可行的解决方案。

    1. 获取实际路线
    2. 借助“/”分隔符将其转换为数组
    3. 只取数组的第二项(第一项总是空的,因为路径的第一个字符是'/')

    【讨论】:

      猜你喜欢
      • 2015-05-22
      • 1970-01-01
      • 1970-01-01
      • 2016-05-21
      • 1970-01-01
      • 1970-01-01
      • 2013-06-12
      • 2021-11-25
      相关资源
      最近更新 更多