symfony - 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')
。这并不重要,但我希望有类似的东西。
解决方案
根据您到底想要什么以及您希望它有多灵活,命名路由可能会有所帮助:
<?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
}
}
推荐阅读
- javascript - Cell.getValue 没有正确比较值
- reactjs - 在 React.js 项目中下载 PDF
- python - 如果一个表中的时间戳介于另一个表中的两个时间戳之间,则使用 Python Pandas 递增 1
- javascript - React-Redux 操作 - 期望 `onClick` 侦听器是一个函数,而不是获得 `object` 类型的值
- node.js - 为什么处理异步等待需要这么长时间
- reactjs - 如何在没有 fowardRef 的情况下从父级访问子级引用
- c++ - 在 C++ 中找不到内存泄漏的原因
- node.js - 从邮递员发送 application/x-www-form-urlencoded 时读取 req.body 内容时发出问题——bodyparser 已使用
- android - Android Studio 未显示版本控制选项
- descriptor - 无法读取 ch.qos.logback:logback-classic:jar:1.2.3 的工件描述符