我正在寻找一个用Symfony控制器实现DI的具体示例。。。https://symfony.com/doc/3.4/controller/service.html没有多大帮助。
配置
search_service:
class: AcmeMyBundleServicesSearchService
search_controller:
class: AcmeMyBundleControllerSearchController
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
感谢任何帮助:(
您的控制器不工作,因为您没有命名空间。因此,在开始时,添加正确的名称空间,但使用手动连接注入参数仍然会有问题,因为您扩展了基本控制器。
最好只使用自动布线,这样你就不需要从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
AppBundleController:
resource: '../../src/AppBundle/Controller'
tags: ['controller.service_arguments']
ps。此外,我建议根本不要扩展基本控制器,因为这样会得到太多实际上不需要的依赖关系。最好通过接线获得树枝、服务和您需要的一切。
我必须进行以下更改才能使其适用于我的3.4安装:
更改资源相对路径
AcmeMyBundleController:
resource: '../../Controller'
tags: ['controller.service_arguments']
将控制器的"名称"更改为完整类名
AcmeMyBundleControllerSearchController:
class: AcmeMyBundleControllerSearchController
arguments: ['@search_service']