带占位符的路由
使用 YAML:
# app/config/routing.yml
blog_show:
path: /blog/{slug}
defaults: { _controller: AppBundle:Blog:show }
使用注释:
// src/AppBundle/Controller/BlogController.php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class BlogController extends Controller
{
/**
* @Route("/blog/{slug}", name="blog_show")
*/
public function showAction($slug)
{
// ...
}
}
任何 URL 匹配/blog/*的请求都将由 AppBundle 中的 BlogController 的 showAction() 方法处理。控制器操作将接收占位符的值作为方法参数。
例如,对/blog/my-post 的请求将触发使用包含值 my-post 的参数 $slug 调用 showAction()。使用该参数,控制器操作可以根据占位符的值更改响应,例如通过从数据库中检索带有 slug my-post 的博客文章。