最佳实践Symfony2实体管理

时间:2015-06-17 08:51:24

标签: symfony

在Symfony2中有很多方法可以管理实体,但我不知道哪个更好

解决方案1:在控制器中

public function myAction()
{
    $myEntity = new MyEntity();
    $form = $this->createForm($myEntityType, $myEntity);

    ...

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager()
        $em->persist($myEntity);
        $em->flush()
    }

    ...
}

解决方案2:使用自定义entityManager

public function myAction()
{
    $myEntityManager = $this->get('manager.my_entity');
    $myEntity = $myEntityManager->create();
    $form = $this->createForm($myEntityType, $myEntity);

    ...

    if ($form->isValid()) {
        $myEntityManager->update($myEntity);
    }

    ...
}

解决方案3:使用工厂

public function myAction()
{
    $myEntityFactory = $this->get('factory.my_entity');
    $myEntity = $myEntityFactory->create();
    $form = $this->createForm($myEntityType, $myEntity);

    ...

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager()
        $em->persist($myEntity);
        $em->flush()
    }

    ...
}

我更喜欢解决方案2,但人们告诉我这不是一个单一的责任模式,因为你有一个工厂和一个方法来更新它。解决方案可能是在管理器中使用工厂,但它带来了很多复杂性。

2 个答案:

答案 0 :(得分:0)

控制器

public function myAction()
{
    $myEntity = $this->get('entity_repository')->getBySomething();
    $form = $this->createForm($myEntityType, $myEntity);

    ...

    if ($form->isValid()) {
        $this->get('entity_persister')->updateEntity($myEntity);
    }

    ...
}

您的存储库只负责为您提供模型对象。 域名服务' entity_persister'负责将给定数据保存到模型中

请注意,此解决方案不是最简洁的方法,因为您的表单直接映射到表示数据库表的对象。我建议如果你想拥有一个更清晰的架构来保持模型对象和由表单映射的对象不同。

答案 1 :(得分:0)

完全取决于用例IMO。没有单一的“最佳方式”。

问题是:你在应用中对这个实体做了什么?您需要多少次访问相同的方法?

如果只在一个地方,那么创建一个服务或控制器之外的任何东西都可能完全不合时宜。

工厂设计模式有其自身的用途,因此需要分析(无论实体)是单独的事情。

但是,当你需要创建一个实体时,我会选择大多数用例的第一个选项:

$myEntity = new MyEntity();

为什么呢?因为代码不会隐藏任何内容。来吧,MyEntity只是一个普通对象,它不需要任何服务或经理或(在大多数情况下)工厂。其他两个似乎是一个不好的做法,因为他们隐藏了那里真正发生的事情(除非需要工厂)。