mar*_*z08 2 php routing symfony symfony4
在我的应用程序中,我使用Symfony4。我希望Symfony在两个目录(A和B)中搜索控制器。我发现了以下内容:
controllers:
resource: '../src/DirectoryA/Controller/'
type: annotation
Run Code Online (Sandbox Code Playgroud)
,但仅适用于一个目录。如何让Symfony在两个目录中搜索控制器?
问候
接受的答案当然是完全正确的。
但是,一旦您从一个控制器目录转移到多个目录,更新 services.yaml 文件可能会有点麻烦。即使必须有专门用于控制器的目录也会受到限制。
这是一种替代方法,它允许在您想要的任何地方创建控制器并自动标记它们。
从一个空的控制器接口开始进行标记。
interface ControllerInterface {}
Run Code Online (Sandbox Code Playgroud)
现在让你所有的控制器实现接口
class Controller1 implements ControllerInterface { ...
class Controller2 implements ControllerInterface { ...
Run Code Online (Sandbox Code Playgroud)
然后调整内核以使用控制器标签自动标记所有控制器接口类。
# src/Kernel.php
protected function build(ContainerBuilder $container)
{
$container->registerForAutoconfiguration(ControllerInterface::class)
->addTag('controller.service_arguments')
;
}
Run Code Online (Sandbox Code Playgroud)
而且很快。你可以在任何你想要的地方创建你的控制器,而没有在 services.yaml 中。
更新:如果您想避免编辑 Kernel.php,那么您可以使用services.yaml 文件中的_instanceof功能。
#config/services.yaml
services:
_instanceof:
App\Contract\ControllerInterface:
tags: ['controller.service_arguments']
Run Code Online (Sandbox Code Playgroud)
另一个更新:只要您的控制器扩展了 Symfony 的 AbstractController,则不需要额外的标记。如果需要,您甚至可以删除默认 services.yaml 文件中的默认控制器行。
在你的 config/services.yaml
App\DirectoryA\Controller\: # assuming you have namespace like that
resource: '../src/DirectoryA/Controller'
tags: ['controller.service_arguments']
App\DirectoryB\Controller\: # assuming you have namespace like that
resource: '../src/DirectoryB/Controller'
tags: ['controller.service_arguments']
Run Code Online (Sandbox Code Playgroud)
这将为服务参数添加下一个目录。那就是根据您的问题回答的。在目录中,您发布的内容是路由文件,类似
controllers_a:
resource: '../src/DirectoryA/Controller/'
type: annotation
controllers_b:
resource: '../src/DirectoryB/Controller/'
type: annotation
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1046 次 |
| 最近记录: |