How can I make persistence easy in Symfony2?

I am currently playing with Symfony2 and so much so far. One question arose, although I wonder what the best practice would be.

If I want to save the object, I need to do the following:

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

This seems to be a lot of code that needs to be done over and over again. I would prefer something like this:

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

However, based on how I need to get an entity manager, this seems far from best practice. So what should I do? Any tips on how you deal with this?

+6
source share
2 answers

This is the standard way to do this to ensure that problems are separated appropriately. Entities do not need to know about the level of conservation.

What you can easily do is add the shortA persistAndFlush method to your controller class if you really have a lot of code that creates and saves new objects.

+11
source

Also, remember that the flush method actually updates your changes to the database. This means that if you need to save several objects, it is better to make one reset at the end of each save operation.

Say you have three objects: $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 will work better because it will only sync your database once:

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

Therefore, having a shortcut in your controller, such as persistAndFlush , should be used with caution, because it is inefficient when you need to save multiple objects. This is stated here in the Doctrine2 documentation (3/4 page). Here's a text taken from official documentation 2.0:

Do not call a flash after every change to the entity or every single call to persist / remove / merge / ... This is an anti-template and unnecessarily reduces the performance of your application. Instead, form units of work that work with your objects and trigger a flash when you are done. When servicing a single HTTP request, it is usually not necessary to call a reset more than 0-2 times.

Regards, Matt

+6
source

Source: https://habr.com/ru/post/889385/


All Articles