symfony - 将 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
任何帮助表示赞赏:)
解决方案
您的控制器不起作用,因为您没有 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']
附言。另外,我建议根本不要扩展基本控制器,因为这样你会得到太多你实际上不需要的依赖项。最好通过接线来获得树枝、服务和所需的一切。
推荐阅读
- python - 为什么我在使用 pip 安装 python 包时没有获得最新版本的 python 包?
- ms-access - 如何在 Microsoft Access 中将多个表(作为子字段)关联到一个表(作为主字段)?
- javascript - 如何更新(添加和删除)redux 嵌套列表中的项目:Redux、React
- java - java.lang.NumberFormatException:对于输入字符串:“”用于将编辑文本中给出的字符串转换为长字符串
- bash - 使用 SSH 从私有仓库自动克隆 Git
- python - 使用 matplotlib LogLocator 绘制 xarray 多维数据
- android - 在谷歌加载其 SignInIntent 时添加 progressBar
- php - 如何使用phpquery从数组中的标签中获取属性、值和文本
- javascript - 如何在Javascript中重新绑定()相同的功能?
- python - 来自 pandas DF 的表格 png 文件