Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 925
sprain Avatar asked May 30 '11 14:05

sprain


1 Answers

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.

like image 186
Seldaek Avatar answered Sep 18 '22 12:09

Seldaek