sajad torkamani

EntityManager#persist()

EntityManager#persist() tells the EntityManager to start managing the persistence of an entity. Invoking the persist method on an entity doesn’t execute a SQL statement until the EntityManager#flush() method is invoked.

Source code

EntityManager#flush()

EntityManager#flush initiates a transaction whereby Doctrine flushes all changes to objects that have been queued up to now to the database. This essentially synchronizes Doctrine’s in-memory state of managed objects with the database.

Managed objects consist of:

  • Any entity that was explicitly persisted by prior persist() calls.
  • Any entity retrieved from the entity managed and modified since retrieval. Doctrine keeps track of these entities.

Source code

Why the two-step process?

Having a two-step process of persist and flush like in the snippet below lets you combine multiple database writes into a single transaction – thereby improving write-performance.

<?php
$user = new User;
$user->setName('Michael Scott');

$company = new Company;
$company->setName('Dunder Mifflin');

$em->persist($user);
$em->persist($company);
$em->flush();

Sources

Tagged: Doctrine