在Symfony控制器上使用DI

时间:2018-11-07 10:46:04

标签: symfony dependency-injection

我正在寻找一个使用Symfony控制器实现DI的具体示例... https://symfony.com/doc/3.4/controller/service.html并没有太大帮助。

配置

search_service:
    class:        Acme\MyBundle\Services\SearchService

search_controller:
    class:        Acme\MyBundle\Controller\SearchController
    arguments:    ['@search_service']

控制器

// Acme/MyBundle/Controllers/SearchController.php

class SearchController extends Controller
{
    public function __construct(SearchService $searchService)
    {
        $this->searchService = $searchService;
    }
}

给我:

Type error: Argument 1 passed to Acme\\MyBundle\\Controller\\SearchController::__construct() must be an instance of Acme\\MyBundle\\Services\\SearchService, none given

任何帮助表示赞赏:)

2 个答案:

答案 0 :(得分:1)

您的控制器不起作用,因为您没有名称空间。因此,一开始要添加正确的名称空间,但是通过扩展手动控制器来插入参数仍然存在问题。

更好地使用自动装配,您无需从services.yml定义依赖项,它将轻松地与控制器配合使用。

这里是例子

  # app/config/services.yml
services:
    # default configuration for services in *this* file
    _defaults:
        # automatically injects dependencies in your services
        autowire: true
        # automatically registers your services as commands, event subscribers, etc.
        autoconfigure: true
        # this means you cannot fetch services directly from the container via $container->get()
        # if you need to do this, you can override this setting on individual services
        public: false

    # makes classes in src/AppBundle available to be used as services
    # this creates a service per class whose id is the fully-qualified class name
    AppBundle\:
        resource: '../../src/AppBundle/*'
        # you can exclude directories or files
        # but if a service is unused, it's removed anyway
        exclude: '../../src/AppBundle/{Entity,Repository}'

    # controllers are imported separately to make sure they're public
    # and have a tag that allows actions to type-hint services
    AppBundle\Controller\:
        resource: '../../src/AppBundle/Controller'
        tags: ['controller.service_arguments']

ps。另外,我建议根本不要扩展基本控制器,因为那样您会获得实际上不需要的过多依赖关系。更好地通过连接它们来获取树枝,服务和您所需的一切。

答案 1 :(得分:0)

我必须进行以下更改才能使其在我的3.4安装中正常工作:

更改资源相对路径

Acme\MyBundle\Controller\:
    resource: '../../Controller'
    tags: ['controller.service_arguments']

将控制器的“名称”更改为完整的类名

Acme\MyBundle\Controller\SearchController:
    class:        Acme\MyBundle\Controller\SearchController
    arguments:    ['@search_service']
相关问题