首页 文章

如何在Symfony 4中为许多路由添加前缀

提问于
浏览
2

我希望命名空间“App \ Controller \ Api”中的所有Controller操作路由都有前缀'/ api' . 我还想在控制器内部使用注释来设置路由的其余部分 .

在Symfony 3中,这是通过编辑'config / routing.yml'来完成的:

app:
    resource: '@AppBundle/Controller/Api'
    type: annotation
    prefix: /api

我怎么能在Symfony 4中这样做?我需要捆绑吗?我会使用哪个配置文件,因为我没有'config / routing.yml'?

2 回答

  • 4

    好吧看起来我应该尝试真正的路径名称 . 以下工作在“config / routes.yaml”中:

    api:
        prefix: /api
        resource: '../src/Controller/Api'
    
  • 1

    首先运行 composer require annotations 然后

    // src/Controller/BlogController.php
    namespace App\Controller;
    
    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    use Symfony\Component\Routing\Annotation\Route;
    
    /**
    * @Route("/blog")
    */
    class BlogController extends Controller
    {
        /**
         * Matches /blog exactly
         *
         * @Route("/", name="blog_list")
         */
        public function list()
        {
            // ...
        }
    
        /**
         * Matches /blog/*
         *
         * @Route("/{slug}", name="blog_show")
         */
        public function show($slug)
        {
            // $slug will equal the dynamic part of the URL
            // e.g. at /blog/yay-routing, then $slug='yay-routing'
    
            // ...
        }
    }
    

相关问题