实体内部的Symfony2-entityManager

时间:2015-12-16 07:06:46

标签: symfony

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

  1. firstname
  2. 名字
  3. identificationCode等
  4. 我创建了一个回调函数,用于验证 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(); ,错误就像尝试调用名为“getDoctrine”的未定义方法类“XXX \ EmployeeBundle \ Entity \ EmployeeBasicInfo”。。请告诉我有效的方法

2 个答案:

答案 0 :(得分:3)

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

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

EntityManager,要查询的存储库等等。无论什么服务都适合你。

查看how to create custom constraint validators with dependencies

答案 1 :(得分:0)

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

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');

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

相关问题