Symfony 4.1组件 - 依赖注入问题

问题描述 投票:2回答:2

我正在重构PHP中的旧应用程序。

我正在尝试使用Symphony依赖注入组件将服务注入控制器(或其他服务),但我不知道如何实现这一点,因为symphony文档比框架组件更适合使用框架。

我已经拥有自己的内核,包含所有服务和控制器的容器(控制器已经注册为服务)。我的控制器从symfony/frameworkbundle扩展AbstractController。所以我现在唯一能做的就是:

通过$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

有人可以使用Symfony组件(不是Symfony框架)帮助我实现DI实现吗?好的工作实例就足够了。或者只是请你的评论我的要点,我试着解决这个问题。

php symfony dependency-injection
2个回答
1
投票

根据您的问题和评论,我认为您需要做的就是修复自动装配。

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'
    # ...

Where to Continue Reading


-1
投票

https://symfony.com/doc/current/service_container.html#fetching-and-using-services

您需要更改服务的默认配置以使其公开:

services:
    _defaults:
        public: true

但访问服务的更优雅方式是将它们注入控制器操作:

public function myAction(Request $request, TestService $service)
© www.soinside.com 2019 - 2024. All rights reserved.