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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With