【问题标题】:Symfony2-entityManager inside an Entity实体内的 Symfony2-entityManager
【发布时间】:2015-12-16 07:06:46
【问题描述】:

我正在使用 Symfony 2.7.6 版。我创建了一个名为 EmployeeBasicInfo 的实体,其中包含字段

  1. 名字
  2. 姓氏
  3. 识别码等

我创建了一个回调函数来验证 EmployeeBasicInfo 实体本身中的识别码,它看起来像

    /**
     * @Assert\Callback(groups={"edit_myinfo"})
     */
    public function validateIdentificationCode(ExecutionContextInterface $context)
    {


        if ($this->getEmployeeFirstName() == 'fakename') {

            $context->buildViolation('This name sounds totally fake!')
                ->atPath('employeeFirstName')
                ->addViolation();


        }
    }

而且这个回调函数可以正常工作

实际上我想要这样一个回调功能,它可以根据数据库检查识别码。我在回调函数中添加了 $em = $this->getDoctrine()->getManager(); ,错误就像 Attempted to call an undefined method named "getDoctrine" of class “XXX\EmployeeBundle\Entity\EmployeeBasicInfo”。。请告诉我有效的方法

【问题讨论】:

    标签: symfony


    【解决方案1】:

    不要在您的实体中注入 EntityManager。 DataMapper-Pattern 的一个基本概念是,您的实体不必知道您的数据源及其连接器。

    我建议编写一个自定义验证约束,在其中注入所需的依赖项。

    EntityManager、要查询的存储库等。任何适合您的服务。

    看看how to create custom constraint validators with dependencies

    【讨论】:

    • 在这种情况下我不能从控制器添加回调函数
    • 我尝试在存储库类中添加相同的内容。但是遇到了同样的错误
    • 我已经引用了这个链接knpuniversity.com/screencast/question-answer-day/…。在其中,他们从实体存储库类连接到数据库,但我仍然收到错误
    • 如何在回调函数内的实体中使用它??
    【解决方案2】:

    我建议您使用服务来执行此操作

    class EmployeeUtility($connection)
    {
        public function __construct($conn) { $this->connection = $v; }
    
        public function validateIdentificationCode($emloyeeId, $validationCode)
        {
            // Your code here
        }
    }
    

    在您的控制器中,您注入服务:

    $employeeUtility = $this->get('employee.utility');
    $employeeUtility->validateIdentificationCode(1,'GF38883dkDdW3373d');
    

    或者,将代码添加到存储库类中。

    【讨论】:

      猜你喜欢
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-10
      • 1970-01-01
      • 1970-01-01
      • 2017-05-07
      相关资源
      最近更新 更多