Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a Doctrine entity is persisted?

Tags:

doctrine-orm

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) {     } } 
like image 391
ezraspectre Avatar asked Jul 12 '13 11:07

ezraspectre


People also ask

What is persist Doctrine?

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.

What is persist flush?

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.

What is Entity Manager in Doctrine?

The EntityManager is the central access point to ORM functionality. It can be used to find, persist, flush and remove entities.

How Doctrine works?

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.


2 Answers

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); 
like image 196
Florian Klein Avatar answered Oct 01 '22 19:10

Florian Klein


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); } 
like image 36
Seth Battin Avatar answered Oct 01 '22 20:10

Seth Battin