首页 > 解决方案 > 将 DI 与 Symfony 控制器一起使用

问题描述

我正在寻找一个使用 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

任何帮助表示赞赏:)

标签: symfonydependency-injection

解决方案


您的控制器不起作用,因为您没有 namespace。所以一开始,添加正确的命名空间,但是手动连接注入参数仍然会有问题,因为你扩展了基本控制器。

最好只使用自动装配,这样您就不需要从 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']

附言。另外,我建议根本不要扩展基本控制器,因为这样你会得到太多你实际上不需要的依赖项。最好通过接线来获得树枝、服务和所需的一切。


推荐阅读