【问题标题】:Symofny 3 - parent::__construct() cant be injectedSymfony 3 - parent::__construct() 无法注入
【发布时间】:2019-11-02 05:41:39
【问题描述】:

我正在尝试将一项服务注入另一个服务以从中调用函数,但它会引发错误:

类型错误:传递给 App\Base\Service\Shop\ShopService::__construct() 的参数 1 必须是 App\Base\Service\AccountService 的实例,给定的 ContainerSgqv3vy\appDevDebugProjectContainer 实例

而且我认为我正确地实现了一切:

use App\Base\Service\AccountService;
use App\Base\Service\BaseService;


class ShopService extends BaseService
{
/**
 * @param AccountService $accountService
 */
public function __construct(AccountService $accountService)
{
    parent::__construct();
    $this->accountService = $accountService;
}

并从中调用我的函数:

this->accountService->getMyFunction();

还有我的实例化类:

    class BaseService
{
    /** @var ContainerInterface  */
    var $container;
    var $em;

public function __construct(ContainerInterface $container, EntityManagerInterface $em)
{
    $this->container = $container;
    $this->em = $em;
}

service.yml

app.shop:
  class: App\Base\Service\ShopService
  arguments: ["@service_container", "@doctrine.orm.default_entity_manager"]
  public: true

【问题讨论】:

  • 你在哪里实例化那个类?
  • 您似乎只是在实例化类时注入了错误的依赖项。问题在于它被实例化的地方,而不是发布的代码。
  • 我正在实例化现有的服务类 AccountService。我不知道问题出在哪里。你能举个例子吗? @MagnusEriksson
  • 我正在实例化现有的服务类 AccountService。我不知道问题出在哪里。你能举个例子吗? @AndreiLupuleasa
  • 请向我们展示所有相关代码。现在,我们甚至不知道你发布了什么课程。我们可以看到构造函数,它期望构造函数中有一个 AccountService 实例,但仅此而已。我们需要查看您在哪里实例化发布的课程(因为那是您的问题所在)。

标签: php service symfony-3.4


【解决方案1】:

当您扩展具有构造函数参数的类时,您应该保留这些参数并在之后添加任何额外的参数。

例子:

class BaseClass
{
    public function __construct(Foo $foo, Bar $bar) {
        // ....
    }
}

要实例化这个类,你需要传递容器和实体管理器:

$base = new BaseClass($fooInstance, $barInstance);

如果你想扩展这个类,它很可能仍然需要那些依赖项+我们的新依赖项:

class ChildClass extends BaseClass
{
    public function __construct(Foo $foo, Bar $bar, Duck $duck)
    {
        // The parent (BaseClass) requires Foo and Bar, 
        // or it will throw an error
        parent::__construct($foo, $bar);

        $this->duck = $duck;
    }
}

要实例化我们的新 ChildClass,我们需要传递三个参数:

$child = new ChildClass($fooInstance, $barInstance, $duckInstance);

然后,当您在 service.yml 中定义我们的 ChildClass 时,您需要定义所有三个依赖项:

app.childclass:
    class: ChildClass
    arguments: ["Foo", "Bar", "Duck"]
    ...

由于我自己没有使用 Symfony,所以你必须原谅不知道 service.yml 的确切语法,但概念是一样的。

【讨论】:

  • 你给了我一个想法。我只是在参数中添加了它。你救了我。谢谢。 @MagnusEriksson
猜你喜欢
  • 2018-01-22
  • 2018-11-14
  • 1970-01-01
  • 2014-08-26
  • 2010-12-08
  • 1970-01-01
  • 2012-05-20
  • 2014-08-06
  • 2020-07-27
相关资源
最近更新 更多