开发者

How can I make persisting simple in Symfony2?

I'm currently playing around with Symfony2 and like it 开发者_如何学运维very much so far. One question has arisen though and I'm wondering what the best practice would be.

If I want to persist an entity I have to go like this:

<?php
$myEntity = new Entity();
$myEntity->setSomeData('just an example');
$em = $this->get('doctrine')->getEntityManager();
$em->persist($myEntity);
$em->flush();

This seems like an awful lot of code to be done over and over again. What I'd prefer is something like that:

<?php
$myEntity = new Entity();
$myEntity->setSomeData('just an example');
$myEntity->persist();

However, based on how I have to get the entity manager, this seems far from best practice. So what am I supposed to do? Any hints on how you handle it?


This is the standard way to do it to keep a proper separation of concerns. Entities should not know about the persistence layer.

What you can easily do is add a shortcut persistAndFlush method on your controller class though, if you really have that many code that creates and persists new entities.


Also, do not forget that the flush method is actually updating your changes on the database. This means that if your need to persist more than one entities, it is better to do one flush at the end of every persist operation.

Say you have three entities: $entity1, $entity2 and $entity3. Then this code is not optimal:

$em->persist($entity1);
$em->flush();

$em->persist($entity2);
$em->flush();

$em->persist($entity3);
$em->flush();

This code would perform better because it will sync your database just once:

$em->persist($entity1);
$em->persist($entity2);
$em->persist($entity3);

$em->flush();

So having a shortcut in your controller like persistAndFlush should be used with care because it is not efficient when you need to persist more than one entity. This is stated here in the Doctrine2 documentation (at 3/4 of page). Here the text taken from the official 2.0 documentation:

Do not invoke flush after every change to an entity or every single invocation of persist/remove/merge/... This is an anti-pattern and unnecessarily reduces the performance of your application. Instead, form units of work that operate on your objects and call flush when you are done. While serving a single HTTP request there should be usually no need for invoking flush more than 0-2 times.

Regards, Matt

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜