Is there a way to determine if a parameter is an object that is already persisted by Doctrine or not? Something like an entity manager method that checks that an object is not a plain old object but actually something already in memory/persisted.
<?php public function updateStatus(Entity $entity, EntityStatus $entityStatus) { $entityManager = $this->getEntityManager(); try { // checking persisted entity if (!$entityManager->isPersisted($entity)) { throw new InvalidArgumentException('Entity is not persisted'); } // ... } catch (InvalidArgumentException $e) { } }
The Doctrine Persistence project is a set of shared interfaces and functionality that the different Doctrine object mappers share. You can use these interfaces and abstract classes to build your own mapper if you don't want to use the full data mappers provided by Doctrine.
Persist and flush flush() . em. persist(entity, flush?: boolean) is used to mark new entities for future persisting. It will make the entity managed by given EntityManager and once flush will be called, it will be written to the database.
The EntityManager is the central access point to ORM functionality. It can be used to find, persist, flush and remove entities.
Doctrine uses the Identity Map pattern to track objects. Whenever you fetch an object from the database, Doctrine will keep a reference to this object inside its UnitOfWork. The array holding all the entity references is two-levels deep and has the keys root entity name and id.
EDIT: As said by @Andrew Atkinson, it seems
EntityManager->contains($entity)
is the preferred way now.
Previous answer: You have to use UnitOfWork api like this:
$isPersisted = \Doctrine\ORM\UnitOfWork::STATE_MANAGED === $entityManager->getUnitOfWork()->getEntityState($entity);
The EntityManager
method contains
serves this purpose. See the documentation (2.4).
In Doctrine 2.4, the implementation looks like this:
class EntityManager { // ... public function contains($entity) { return $this->unitOfWork->isScheduledForInsert($entity) || $this->unitOfWork->isInIdentityMap($entity) && ! $this->unitOfWork->isScheduledForDelete($entity); }
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