How does Doctrine's entity manager and Data Mapper approach differ from Eloquent's Active Record approach in terms of how objects are persisted?
Short answer
In Doctrine, entity classes are plain PHP objects with no knowledge of how they are persisted, and all the actual database interaction, such as saving, updating, or deleting an entity, is handled separately by the entity manager, which tracks changes to entities and synchronizes…
Advertisement
AModel answer
In Doctrine, entity classes are plain PHP objects with no knowledge of how they are persisted, and all the actual database interaction, such as saving, updating, or deleting an entity, is handled separately by the entity manager, which tracks changes to entities and synchronizes them with the database when explicitly told to flush those changes, a clear separation of concerns that some developers prefer since it keeps entity classes focused purely on representing data and business logic rather than mixing in persistence responsibilities.
$user = $entityManager->find(User::class, 1);
$user->setName('Ali');
$entityManager->flush();Real-world example
A Symfony application using Doctrine modifies a fetched User entity's name property directly, and only when the entity manager's flush method is explicitly called does Doctrine actually generate and execute the corresponding database update statement.
Likely follow-ups
- What is the unit of work pattern and how does Doctrine's entity manager use it?
- Why might a team prefer Doctrine's separation of concerns over Eloquent's more convenient Active Record approach?
Related topics