【问题标题】:Symfony2 - Doctrine - Is there any way to save entity in one line?Symfony2 - Doctrine - 有没有办法将实体保存在一行中?
【发布时间】:2012-08-18 15:34:37
【问题描述】:

用教义拯救实体我应该这样做

$em = $this->getDoctrine()->getEntityManager();
$em->persist($product);
$em->flush();

但也许我可以以某种方式在一行中做到这一点,例如

$product->save();

或

$this->saveEntity($product);

或

$this->getDoctrineEntityManager()->persistAndFlush($product);

如果我需要自己创建这些方法,那么如何以 symfony 的方式实现呢?

【问题讨论】:

    标签: php symfony doctrine-orm


    【解决方案1】:

    persist() 和flush() 是完全不同的独立操作。当您持久化实体对象时,您是在告诉实体管理器跟踪对象的更改。当您调用flush() 方法时,实体管理器将在单个事务中将实体管理器跟踪的实体对象的更改推送到数据库中。大多数时候实体管理器必须管理多个对象。例如,除了您的product 实体之外,您可能还必须跟踪tag 或cart 实体。每次保存这些实体对象时调用persistAndFlush() 会导致与数据库的多个IO 连接。这不是有效的。所以我认为最好将它们视为单独的操作。

    【讨论】:

    【解决方案2】:

    基于this post(最后写了)你可以将保存代码写入存储库:

    class DoctrineORMCustomerRepository extends EntityRepository implements CustomerRepository
    {
        public function save(Customer $customer)
        {
            $this->_em->persist($customer);
            $this->_em->flush();
        }
    }
    

    【讨论】:

      【解决方案3】:

      如果您在框架包中使用控制器,并在控制器中编写持久性逻辑,则可以使用以下内容扩展 Symfony\Bundle\FrameworkBundle\Controller\Controller

      namespace ExampleNameSpace\Controller;
      
      use Symfony\Bundle\FrameworkBundle\Controller\Controller;
      
      class BaseController extends Controller
      {
          public function persistAndSave($entity)
          {
              $em = $this->getDoctrine()->getEntityManager();
              $em->persist($entity);
              $em->flush();
          }
      }
      

      在所有其他控制器中,您将扩展您的 ExampleNameSpace\Controller\BaseController 而不是 Symfony Frameworkbundle 中的那个。

      另外,我采用的方法是为每个实体编写一个管理器类,该类具有类名和注入的学说实体管理器。每个管理器类都使用以下方法扩展一个抽象管理器类:

      <?php
      
      abstract class AbstractManager
      {
          /**
           * The Entity Manager
           *
           * @var \Doctrine\ORM\EntityManager  The Doctrine Entity Manager
           */
          protected $em;
      
          /**
           * The full class path associated with the repository
           *
           * @var string
           */
          protected $class;
      
          /**
           * The repository for the manager
           *
           * @var \Doctrine\ORM\EntityRepository
           */
          protected $repository;
      
          /**
           * Creates a new instance of the primary class managed by a given
           * manager
           *
           * @return object       A new instance of the entity being managed
           */
          public function create()
          {
              return new $this->class();
          }
      
          /**
           * {@inheritDoc}
           */
          public function save($object, $flush = false)
          {
              if( ! $this->supportsClass($object))
              {
                  throw new \InvalidArgumentException(sprintf('Invalid entity passed to this manager, expected instance of %s', $this->class));
              }
      
              $this->em->persist($object);
      
              if($flush === true)
              {
                  $this->flush();
              }
      
              return $object;
          }
      
          /**
           * {@inheritDoc}
           */
          public function delete($object, $flush = false)
          {
              if( ! $this->supportsClass($object))
              {
                  throw new \InvalidArgumentException(sprintf('Invalid entity passed to this manager, expected instance of %s', $this->class));
              }
      
              $this->em->remove($object);
      
              if($flush === true)
              {
                  $this->flush();
              }
      
              return true;
          }
      
          /**
           * Convenience method providing access to the entity manager flush method
           */
          public function flush()
          {
              $this->em->flush();
          }
      
          /**
           * {@inheritDoc}
           */
          public function supportsClass($object)
          {
              return $object instanceof $this->class || is_subclass_of($object, $this->class);
          }
      
          /**
           * Set class. Setter for dependency injection
           *
           * @param object $class  A class related to this manager
           */
          public function setClass($class)
          {
              $this->class = $class;
          }
      
          /**
           * Set entity manager. Setter for dependency injection
           *
           * @param \Doctrine\ORM\EntityManager $entity_manager
           */
          public function setEntityManager(\Doctrine\ORM\EntityManager $entity_manager)
          {
              $this->em = $entity_manager;
          }
      
          /**
           * Returns the repository
           *
           * @return \Doctrine\ORM\EntityRepository    A Doctrine Repository for the
           *                                          class related to this Manager
           */
          protected function getRepository()
          {
              if( ! $this->repository)
              {
                  $this->repository = $this->em->getRepository($this->class);
              }
      
              return $this->repository;
          }
      }
      

      管理器在依赖注入容器中配置,为实体提供适当的类,并提供创建、保存和删除他们负责的实体的访问权限,以及访问存储库的权限。

      可以在具有管理器的控制器中创建一个实体,如下所示:

      public function createAction(Request $request)
      {
          $entityManager = $this->get('some.entity.manager');
      
          $entity = $entityManager->create();
      
          $form = $this->createForm(new EntityForm(), $entity);
      
          $form->bindRequest($request);
      
          if($form->isValid())
          {
              $entityManager->save($entity, true);
          }
      }
      

      【讨论】:

      • CRUD 操作不是仓库的工作吗?我不认为增加一个额外的“经理”是最好的选择。对于每个实体,您最终将拥有一个存储库、一个控制器和一个“管理器”。不确定,但它似乎过于工程化。
      • 我的理解是存储库是用于只读操作的。对于非常简单的 crud 操作可能过于复杂,但在更复杂的应用程序中,这种模式允许将您的业务逻辑与控制器和存储库类分离,并使单元测试更容易
      • 我明白你的意思。你的manager 是Service Layer 的一部分,我确实在我的应用程序上使用了服务层(不是一个symfony 2 调用“控制器作为服务,也不是服务容器/DI)。看看你的manager 作为服务层它似乎很合理。无论哪种方式,您都不会发现存储库是只读的(有吗?)。它可以容纳对您的数据的所有操作。这取决于您的架构,这是一个选择问题。对于简单的应用不需要服务层。为什么简单的 CRUD 操作会过于复杂?
      • 如果这个方法是私有的会更好
      【解决方案4】:

      我知道你的愿望。第一次使用单个保存方法看起来不错。

      但是,如果您有 2 种方法,则可以在将语句发送到数据库之前收集它们。我猜这不是学说的实际工作,但也许通过更新你可以使用flush(“together”)。这样可以节省大量开销。

      【讨论】:

      • 这是如何工作的?据我了解 - 这是准备好的陈述。而当我们调用persist的时候,它仍然调用数据库,对吧?因此,对于每条语句,都会调用一个数据库。这如何节省大量开销?是不是因为最后带有 flush 的那些调用更快,所以即使有很多调用 - 总体上它更快?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-24
      相关资源
      最近更新 更多