3

我在 Symfony 4 应用程序中找不到任何有关全局路由前缀的信息。我发现的唯一一件事@route是用. 但我不使用注释,我需要所有控制器都具有相同的前缀。

现在我可以在文件中像这样在 S3 中执行此app/config/routing.yml操作:

app:
    resource: '@AppBundle/Controller/'
    type: annotation
    prefix: /foo

但是 S4 是无捆绑的,我不能这样做——我必须创建一个我不需要的捆绑。

是否可以在 Symfony 4 中定义全局路由前缀,或者我最终会为每个根添加前缀/创建自定义路由加载器,特别是如果我在 YAML 中配置路由?

4

4 回答 4

7

这适用注释,给每个控制器 'this/prefix' :

# file: config/routes/annotations.yaml

controllers:
    resource: ../../src/Controller/
    type: annotation
    prefix: this/prefix

然后对于导入的路由,“this/prefix”将应用于下面的所有 FOSUserBundle 路由(是的,我测试过)。

# file: config/routes.yaml

fos_user:
    resource: "@FOSUserBundle/Resources/config/routing/all.xml"
    prefix: this/prefix

如果您不使用注释,您应该能够导入单独的路由文件(可以导入更多),将前缀应用于资源中的所有内容。但是删除“@”符号并使用文件的相对路径。'this/prefix' 的值可以配置为服务容器参数,请看这里:http ://symfony.com/doc/current/routing/service_container_parameters.html

于 2018-02-24T11:52:04.597 回答
6

我可能不理解这个问题,因为我不知道您为什么要在应用程序中使用全局前缀。即使您使用的是 yaml 而没有包,您也可以在导入路由文件时设置前缀。

# config/routes.yaml
blog:
    resource: '../src/Resources/config/routes/blog.yaml'
    prefix: blog

# src/Resources/config/routes/blog.yaml
blog_show:
    path: /show
    controller: App\Controller\BlogController::show

blog_list:
    path: /list
    controller: App\Controller\BlogController::list

bin/console debug:router 会产生

blog_show          ANY      ANY      ANY    /blog/show     
blog_list          ANY      ANY      ANY    /blog/list  

但同样,我怀疑你在要求别的东西。也许您可以在您的问题中添加一个示例?

于 2018-01-05T21:08:18.517 回答
2

有几种方法可以实现任何路由的前缀。它们的不同主要在于它们所针对的路线类型。

对于由注释定义的路由,您需要编辑config/routes/annotations.yaml 并放置prefix: your-prefix键值对。

对于由 YAML 列表定义的路由,您需要在新的路由键值对config/routes.yaml下编辑 put并创建包含所有路由的文件,然后从使用.prefix: your-prefixresource: "routes/routes-that-you-want-to-be-prefixed.yaml"routes/routes-that-you-want-to-be-prefixed.yamlconfig/routes.yamlresource: "routes/routes-that-you-want-to-be-prefixed.yaml"

如果您赶时间并想要检查前缀,您也可以使用快速而肮脏的方法。编辑src/Kernel.php所有后缀$routes->import(..)->prefix('your-prefix)无需更改任何路由文件)

我用一些示例代码示例写了一个全面的描述作为对这个问题的回答: Running Symfony 5 with reverse proxy in subdirectory

示例代码片段已经针对Symfony 4.4Symfony 5.1进行了测试,并且没有任何问题。

于 2020-09-29T15:21:39.470 回答
0

我有同样的问题,并且无法使用 yaml 配置解决它,但我让它在类的顶部添加一个注释,如下所示:

/**
 *
 * Rest\Route("/api")
 */
class TestController extends FosRestController
{
   /**
     * @Rest\Route("/test", name="tm_test")
     * @Method({"GET"})
     */
    public function testAction()
    {
        ...
    }

}

/api/test这将为testAction()

看这篇文章:https ://symfony.com/blog/new-in-symfony-3-4-prefix-all-controller-route-names

希望能帮助到你

于 2018-03-09T14:46:25.083 回答