首页 > 解决方案 > Symfony 4 - Custom Folder structure and Services

问题描述

I'm looking to implement a folder structure recommended by Nikola Posa.

The structure I would like is something like what is below.

src/
   Domain/
      User/
         UserEntity.php
         UserController.php
      Pages/
         DefaultPageController.php

The idea is to logically group/namespace features or similar content. I seem to be getting this error:

The file "../src/Controller" does not exist (in: /Users/dev/Sites/web/html/sandbox/php/crud/config) in /Users/dev/Sites/web/html/sandbox/php/crud/config/services.yaml (which is loaded in resource "/Users/dev/Sites/web/html/sandbox/php/crud/config/services.yaml").

I'm not sure how important it is to wire up these as services. If I comment out the App\Controller property of the services.yaml, it goes away.

How can I load controllers in service.yaml with a src/Domain/Feature/FeatureController.php structure?

标签: symfonysymfony4

解决方案


您当然可以去老学校,只需单独定义每个控制器服务:

# config/services.yaml
Domain\Feature\FeatureController:
    tags: ['controller.service_arguments']

但是,一旦您习惯了自动装配,那么拼写每个服务就会很痛苦。作为替代方案,您可以使用自动配置功能将控制器标记添加到选定的类。首先声明一个空接口并让你的控制器实现它:

interface ControllerInterface {}

class SomeController implements ControllerInterface

然后调整 src/Kernel.php

# src/Kernel.php
class Kernel {
    protected function build(ContainerBuilder $container)
    {
        $container->registerForAutoconfiguration(ControllerInterface::class)
            ->addTag('controller.service_arguments');

当然,这只是处理控制器问题。您可能会遇到许多其他与自动装配相关的问题。


推荐阅读