【问题标题】:Missing argument 1 for method with argument being a service injection in Symfony 3Symfony 3 中参数为服务注入的方法缺少参数 1
【发布时间】:2017-05-20 23:55:56
【问题描述】:

我将此类服务链接到我的实体中的一种方法:

entity_form:
    class: AppBundle\Entity\EntityForm
    calls:
         - [setDoctrine, ['@doctrine']]

参数将(或至少应该)doctrine 注入到我的实体中,以便我可以从 db 内部方法中获取内容。

我为 getter 设置了它,因为我不得不省略在 __construct 中设置参数,因为在代码中该类永远不会真正“构造”

实体本身如下所示:

<?php
namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
/**
 * @ORM\Entity
 * @ORM\Table(name="entity_form")
 */
class EntityForm
{

    protected $id;

    protected $url;

    protected $name;

    protected $className;

    protected $description;

    private $doctrine;


    public function getId()
    {
        return $this->id;
    }

    /* _All Getters An Setters Here.._ */

    private function setDoctrine($doctrine)
    {
        return $doctrine;
    }

    public function createEntity($id)
    {
        $this->setDoctrine();

        $entityPath = sprintf('AppBundle:%s:%s', __NAMESPACE__, $this->getClassName());

        var_dump($this->doctrine);
        exit;
        //var_dump is temponary and only for testing the doctrine 

        $entity = $this->doctrine->getRepository($entityPath)->find($id);

        return $entity;
    }
}

该实体存储有关网站上表格的信息。有了这个,我想从给定的 Id 中快速创建表单的类实体。


很遗憾

运行这样的代码会给我这个错误:

警告:缺少参数 1 AppBundle\Entity\EntityForm::setDoctrine(),调用 C:\PHP\Repos\centaur\src\AppBundle\Entity\EntityForm.php 在第 139 行 并定义


发生此错误的原因可能是什么?我该如何解决?

任何帮助都会很棒

【问题讨论】:

    标签: php symfony oop doctrine symfony-3.2


    【解决方案1】:

    该论点将(或至少应该)教义注入我的实体,因此 我可以从数据库内部方法中获取东西。

    没有。

    您定义的 entity_form 服务只不过是 AppBundle\Entity\EntityForm 与 setter-injected doctrine 服务。

    所以你的EntityForm 注入服务在容器中可用,它不会被注入到每个创建的EntityForm 中。

    看来您应该阅读更多有关职责的信息。你想在createEntity方法中实现的应该是应用服务层的一部分,而不是模型本身。

    模型不了解应用程序/基础架构概念,因此注入 ORM 是不行的。

    关于提到的错误,只考虑服务定义和调用:

    $this->setDoctrine();
    

    您想在没有必需参数的情况下调用 setter,并且可能错过了您的服务定义已经进行了 setter-injection。

    正如我之前提到的,实体基本上不是服务,所以将这部分移动到特定的类中,并使用标准 DI 在那里注入与数据库相关的服务。

    【讨论】:

    • 您的回答没有提供任何真正的解决方案。
    • @aln447 在很大程度上,除了从 Doctrine 切换到主动记录方法之外,没有真正的解决方案。
    • 我向您解释了为什么您的方法不合适,并向您展示了可能的方法。如果由于设计和对特定技术工作原理的误解而导致实施不起作用,我认为这是一种有效的回答方式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-24
    • 2017-10-05
    相关资源
    最近更新 更多