Symfony2 - Doctrine - Is there any way to save entity in one line?

Viewed 35337

To save entity with doctrine I should do like this

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

But maybe I can somehow do that in one line like

$product->save();

or

$this->saveEntity($product);

or

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

If I need to create this methods by my self then how to do that in symfony way?

4 Answers

Based on this post (it’s written about it at the very end) you can write the save code to the repository:

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