我正在用 PHP 重构旧应用程序。
我正在尝试使用 Symfony 依赖注入组件将服务注入控制器(或其他服务),但我不知道如何实现这一点,因为 symphony 文档比框架组件更适合使用框架。
我已经有了自己的内核,包含所有服务和控制器的容器(控制器已经注册为服务)。我的控制器从 AbstractController 扩展symfony/frameworkbundle
。所以我现在唯一能做的就是:
通过以下方式从容器获取服务$this->container->get('service_id')
,但是如果构造函数中的服务将类作为参数
public function __constructor(SomeClass $someClass)
然后我得到这个异常:
编译容器时,“App\V2\Service\TestService”服务或别名已被删除或内联。您应该将其公开,或者停止直接使用容器并使用依赖项注入。
如果我更改配置以使所有服务公开,那么:
函数 APP\V2\Service\TestService::__construct() 的参数太少,已传递 0 个,预期为 1 个
我准备一个要点,以便更好地理解我在说什么:https://gist.github.com/miedzwin/49bac1cc1d5270d3ba1bfcf700abf864 https://gist.github.com/miedzwin/49bac1cc1d5270d3ba1bfcf700abf864
有人可以帮助我使用 Symfony 组件(不是 Symfony 框架)进行 DI 实现吗?好的工作示例就足够了。或者请把你的评论放在我的要点上,我会尽力解决这个问题。
Symfony 4/5 自动装配方式
根据您的问题和评论,我认为您需要做的就是修复自动装配。
Symfony 4-way 很简单:自动连接所有服务和参数,无需手动设置(如果可能的话)。
要将其应用到您的示例中,这将是满足您的需求和 Symfony 4 的最佳配置:
services:
_defaults:
# pass service dependencies to constructors by default
autowire: true
# add known tags (for commands, event subscribers etc) by default
autoconfigure: true
# to make using tests, bin files and another simpler
public: true
# autowiring of string/array/int parameters to constructors
# this fixes cases like "argument "$facebookUserId" of method "__construct()" has no type-hint, you should configure its value explicitly"
bind:
# $constructorVariableName: %parameter% in config
$facebookUserId: '%facebook_user_id%'
APP\V2\:
resource: '../src/app/V2/*'
exclude: '../src/app/V2/{Script, Trait}'
# symfony services - you still have to setup 3rd paryt services manually
Symfony\Component\DependencyInjection\ParameterBag\ContainerBag:
arguments:
- '@service_container'
# ...
在哪里继续阅读
- 将参数传递给服务 https://stackoverflow.com/a/49084402/1348344
- 如何重构 Symfony 3.3 中新的依赖注入功能 https://www.tomasvotruba.cz/blog/2017/05/07/how-to-refactor-to-new-dependency-injection-features-in-symfony-3-3/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)