Symfony - 如何获得控制器的主要路线?
Symfony - How to get the main route of the controller?
如何只获取 Controller class 的路由?在这种情况下是 /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
}
}
如何只获取 Controller class 的路由?在这种情况下是 /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
}
}