【问题标题】:Problems injecting a custom service into a custom provider with Symfony2使用 Symfony2 将自定义服务注入自定义提供程序时出现问题
【发布时间】:2018-10-14 15:21:30
【问题描述】:

我在使用 Symfony2 的 LdapUserProvider.php 中调用 ImageEncoderService 时遇到问题。在互联网上,我只找到关于如何在存储库、控制器、实体和命令中调用服务的讨论。

这样做:

class LdapUserProvider implements UserProviderInterface
{
    private $ldapManager;
    private $bindUsernameBefore;
    private $userClass;
    private $em;
    private $session;
    private $imgEncoder;

    public function __construct(LdapManagerUserInterface $ldapManager, $bindUsernameBefore = false, $userClass, $em, ImageEncoderService $imgEnconder)
    {
        $this->session = new Session();
        $this->ldapManager = $ldapManager;
        $this->bindUsernameBefore = $bindUsernameBefore;
        $this->userClass = $userClass;
        $this->em = $em;
        $this->imgEnconder = $imgEnconder;
    }
    ...
}

抛出此错误:

ContextErrorException in LdapUserProvider.php line 58:
Catchable Fatal Error: Argument 5 passed to
Foo\ApiBundle\Provider\LdapUserProvider::__construct() 
must be an instance of Foo\ApiBundle\Service\ImageEncoderService,
none given, called in /app/cache/dev/appDevDebugProjectContainer.php 
on line 2202 and defined

甚至可以将服务注入自定义提供程序吗?还是我需要将其注入其他地方,然后在提供程序中使用它?

我正在使用的 LDAP 提供程序是:https://symfony.com/doc/current/security/ldap.html

PS。该服务本身在应用程序的其他地方运行良好,例如命令、控制器等。

【问题讨论】:

    标签: symfony service dependency-injection ldap provider


    【解决方案1】:

    你确定你有这个 API 的类使用声明吗?

    use  Foo\ApiBundle\Service\ImageEncoderService;
    

    尝试删除缓存目录。

    您可以尝试通过 services.yml 服务显式注入。

    用于显式注入其他服务和参数的 Symfony 文档。

    https://symfony.com/doc/current/service_container.html#manually-wiring-arguments

    例子:

         # explicitly configure the service
            #dont remember if you need to register the service like this
            #but should work without this, refer documentation :)
            # ImageService:
            #   class:  Foo\ApiBundle\Provider\LdapUserProvider
    
            Foo\ApiBundle\Provider\LdapUserProvider:
                arguments:
                    $imgEncoder: '@Foo\ApiBundle\Service\ImageEncoderService'
                    #$imgEncoder: '@ImageService'
    

    【讨论】:

    • 谢谢,我已经这样做了,但错误一直出现。我认为这与 Symfony2 LDAP 提供程序中的依赖注入问题有关。
    • 是的,Ldap 用户提供者希望在 cosntruct 中有一些预定义的参数,您可以在 api.symfony.com/4.0/Symfony/Component/Security/Core/User/… 中看到它们
    • 在文档中您可以看到 ldap 类在构造 symfony.com/doc/current/security/ldap.html 中的期望
    • 你能做什么,你可以直接在你的方法中注入你的服务,例如:function someStter($bindUsernameBefore = false, $userClass, $em, ImageEncoderService $imgEnconder),并在你的功能,应该在您的系统中启用自动装配。对于 em,实际上你可以使用 Doctrine\Common\Persistence\ManagerRegistry $em 的依赖注入,然后在你的方法中使用它,然后你只需要获取 manager $em->getRepository()->getManager() 或 $em -> 直接getManager,不记得具体了。
    猜你喜欢
    • 2016-09-02
    • 2014-09-20
    • 1970-01-01
    • 2020-07-31
    • 2018-04-15
    • 2017-07-27
    • 2013-11-01
    • 1970-01-01
    • 2015-12-21
    相关资源
    最近更新 更多