class EntityManager implements EntityManagerInterface (View source)

The EntityManager is the central access point to ORM functionality.

It is a facade to all different ORM subsystems such as UnitOfWork, Query Language and Repository API. Instantiation is done through the static create() method. The quickest way to obtain a fully configured EntityManager is:

use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;

$paths = array('/path/to/entity/mapping/files');

$config = Setup::createAnnotationMetadataConfiguration($paths);
$dbParams = array('driver' => 'pdo_sqlite', 'memory' => true);
$entityManager = EntityManager::create($dbParams, $config);

For more information see {@link http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/configuration.html}

You should never attempt to inherit from the EntityManager: Inheritance is not a valid extension point for the EntityManager. Instead you should take a look at the {see \Doctrine\ORM\Decorator\EntityManagerDecorator} and wrap your entity manager in a decorator.

Methods

__construct(Connection $conn, Configuration $config, EventManager $eventManager)

Creates a new EntityManager that operates on the given database connection and uses the given Configuration and EventManager implementations.

Connection
getConnection()

Gets the database connection object used by the EntityManager.

getMetadataFactory()

Gets the metadata factory used to gather the metadata of classes.

getExpressionBuilder()

Gets an ExpressionBuilder used for object-oriented construction of query expressions.

getIdentifierFlattener()

Gets an IdentifierFlattener used for converting Entities into an array of identifier values.

void
beginTransaction()

Starts a transaction on the underlying database connection.

Cache|null
getCache()

Returns the cache API for managing the second level cache regions or NULL if the cache is not enabled.

mixed
transactional(callable $func)

Executes a function in a transaction.

void
commit()

Commits a transaction on the underlying database connection.

void
rollback()

Performs a rollback on the underlying database connection.

ClassMetadata
getClassMetadata($className)

Returns the ORM metadata descriptor for a class.

createQuery(string $dql = '')

Creates a new Query object.

createNativeQuery(string $sql, ResultSetMapping $rsm)

Creates a native SQL query.

createQueryBuilder()

Create a QueryBuilder instance

merge($object) deprecated

{@inheritDoc}

detach($object) deprecated

{@inheritDoc}

flush()

Flushes all changes to objects that have been queued up to now to the database.

object|null
find(string $entityName, mixed $id, int|null $lockMode = null, int|null $lockVersion = null)

Finds an Entity by its identifier.

object|GhostObjectInterface|null
getReference(string $entityName, mixed $id)

Gets a reference to the entity identified by the given type and identifier without actually loading it, if the entity is not yet loaded.

object
getPartialReference(string $entityName, $id)

Gets a partial reference to the entity identified by the given type and identifier without actually loading it, if the entity is not yet loaded.

clear(null $entityName = null)

Clears the EntityManager. All entities that are currently managed by this EntityManager become detached.

void
close()

Closes the EntityManager. All entities that are currently managed by this EntityManager become detached. The EntityManager may no longer be used after it is closed.

persist(object $entity)

Tells the EntityManager to make an instance managed and persistent.

remove(object $entity)

Removes an entity instance.

refresh(object $entity)

Refreshes the persistent state of an entity from the database, overriding any local changes that have not yet been persisted.

void
lock(object $entity, int $lockMode, int|null $lockVersion = null)

Acquire a lock on the given entity.

ObjectRepository|EntityRepository
getRepository(string $entityName)

Gets the repository for an entity class.

bool
contains(object $entity)

Determines whether an entity instance is managed in this EntityManager.

EventManager
getEventManager()

Gets the EventManager used by the EntityManager.

getConfiguration()

Gets the Configuration used by the EntityManager.

bool
isOpen()

Check if the Entity manager is open or closed.

getUnitOfWork()

Gets the UnitOfWork used by the EntityManager to coordinate operations.

getHydrator(int $hydrationMode)

Gets a hydrator for the given hydration mode.

newHydrator(int $hydrationMode)

Create a new instance for the given hydration mode.

getProxyFactory()

Gets the proxy factory used by the EntityManager to create entity proxies.

initializeObject($obj)

{@inheritDoc}

static EntityManager
create(Connection|mixed[] $connection, Configuration $config, EventManager|null $eventManager = null)

Factory method to create EntityManager instances.

static Connection
createConnection(Connection|mixed[] $connection, Configuration $config, EventManager|null $eventManager = null)

Factory method to create Connection instances.

getFilters()

Gets the enabled filters.

bool
isFiltersStateClean()

Checks whether the state of the filter collection is clean.

bool
hasFilters()

Checks whether the Entity Manager has filters.

Details

protected __construct(Connection $conn, Configuration $config, EventManager $eventManager)

Creates a new EntityManager that operates on the given database connection and uses the given Configuration and EventManager implementations.

Parameters

Connection $conn
Configuration $config
EventManager $eventManager

Connection getConnection()

Gets the database connection object used by the EntityManager.

Return Value

Connection

ClassMetadataFactory getMetadataFactory()

Gets the metadata factory used to gather the metadata of classes.

Return Value

ClassMetadataFactory

Expr getExpressionBuilder()

Gets an ExpressionBuilder used for object-oriented construction of query expressions.

Example:

$qb = $em->createQueryBuilder(); $expr = $em->getExpressionBuilder(); $qb->select('u')->from('User', 'u') ->where($expr->orX($expr->eq('u.id', 1), $expr->eq('u.id', 2)));

Return Value

Expr

IdentifierFlattener getIdentifierFlattener()

Gets an IdentifierFlattener used for converting Entities into an array of identifier values.

Return Value

IdentifierFlattener

void beginTransaction()

Starts a transaction on the underlying database connection.

Return Value

void

Cache|null getCache()

Returns the cache API for managing the second level cache regions or NULL if the cache is not enabled.

Return Value

Cache|null

mixed transactional(callable $func)

Executes a function in a transaction.

The function gets passed this EntityManager instance as an (optional) parameter.

{@link flush} is invoked prior to transaction commit.

If an exception occurs during execution of the function or flushing or transaction commit, the transaction is rolled back, the EntityManager closed and the exception re-thrown.

Parameters

callable $func The function to execute transactionally.

Return Value

mixed The value returned from the closure.

Exceptions

Throwable

void commit()

Commits a transaction on the underlying database connection.

Return Value

void

void rollback()

Performs a rollback on the underlying database connection.

Return Value

void

ClassMetadata getClassMetadata($className)

Returns the ORM metadata descriptor for a class.

The class name must be the fully-qualified class name without a leading backslash (as it is returned by get_class($obj)) or an aliased class name.

Examples: MyProject\Domain\User sales:PriceRequest

{@internal Performance-sensitive method. }}

Parameters

$className

Return Value

ClassMetadata

Exceptions

ReflectionException
InvalidArgumentException
MappingException

Query createQuery(string $dql = '')

Creates a new Query object.

Parameters

string $dql The DQL string.

Return Value

Query

NativeQuery createNativeQuery(string $sql, ResultSetMapping $rsm)

Creates a native SQL query.

Parameters

string $sql
ResultSetMapping $rsm The ResultSetMapping to use.

Return Value

NativeQuery

QueryBuilder createQueryBuilder()

Create a QueryBuilder instance

Return Value

QueryBuilder

merge($object) deprecated

deprecated

{@inheritDoc}

Parameters

$object

detach($object) deprecated

deprecated

{@inheritDoc}

Parameters

$object

flush()

Flushes all changes to objects that have been queued up to now to the database.

This effectively synchronizes the in-memory state of managed objects with the database.

If an entity is explicitly passed to this method only this entity and the cascade-persist semantics + scheduled inserts/removals are synchronized.

Exceptions

OptimisticLockException If a version check on an entity that makes use of optimistic locking fails.
ORMException

object|null find(string $entityName, mixed $id, int|null $lockMode = null, int|null $lockVersion = null)

Finds an Entity by its identifier.

Parameters

string $entityName The class name of the entity to find.
mixed $id The identity of the entity to find.
int|null $lockMode One of the \Doctrine\DBAL\LockMode::* constants or NULL if no specific lock mode should be used during the search.
int|null $lockVersion The version of the entity to find when using optimistic locking.

Return Value

object|null The entity instance or NULL if the entity can not be found.

Exceptions

OptimisticLockException
ORMInvalidArgumentException
TransactionRequiredException
ORMException

object|GhostObjectInterface|null getReference(string $entityName, mixed $id)

Gets a reference to the entity identified by the given type and identifier without actually loading it, if the entity is not yet loaded.

Parameters

string $entityName The name of the entity type.
mixed $id The entity identifier.

Return Value

object|GhostObjectInterface|null The entity reference.

Exceptions

ORMException

object getPartialReference(string $entityName, $id)

Gets a partial reference to the entity identified by the given type and identifier without actually loading it, if the entity is not yet loaded.

The returned reference may be a partial object if the entity is not yet loaded/managed. If it is a partial object it will not initialize the rest of the entity state on access. Thus you can only ever safely access the identifier of an entity obtained through this method.

The use-cases for partial references involve maintaining bidirectional associations without loading one side of the association or to update an entity without loading it. Note, however, that in the latter case the original (persistent) entity data will never be visible to the application (especially not event listeners) as it will never be loaded in the first place.

Parameters

string $entityName The name of the entity type.
$id

Return Value

object The (partial) entity reference.

clear(null $entityName = null)

Clears the EntityManager. All entities that are currently managed by this EntityManager become detached.

Parameters

null $entityName Unused. @todo Remove from ObjectManager.

void close()

Closes the EntityManager. All entities that are currently managed by this EntityManager become detached. The EntityManager may no longer be used after it is closed.

Return Value

void

persist(object $entity)

Tells the EntityManager to make an instance managed and persistent.

The entity will be entered into the database at or before transaction commit or as a result of the flush operation.

NOTE: The persist operation always considers entities that are not yet known to this EntityManager as NEW. Do not pass detached entities to the persist operation.

Parameters

object $entity The instance to make managed and persistent.

Exceptions

ORMInvalidArgumentException
ORMException

remove(object $entity)

Removes an entity instance.

A removed entity will be removed from the database at or before transaction commit or as a result of the flush operation.

Parameters

object $entity The entity instance to remove.

Exceptions

ORMInvalidArgumentException
ORMException

refresh(object $entity)

Refreshes the persistent state of an entity from the database, overriding any local changes that have not yet been persisted.

Parameters

object $entity The entity to refresh.

Exceptions

ORMInvalidArgumentException
ORMException

void lock(object $entity, int $lockMode, int|null $lockVersion = null)

Acquire a lock on the given entity.

Parameters

object $entity
int $lockMode
int|null $lockVersion

Return Value

void

Exceptions

OptimisticLockException
PessimisticLockException

ObjectRepository|EntityRepository getRepository(string $entityName)

Gets the repository for an entity class.

Parameters

string $entityName The name of the entity.

Return Value

ObjectRepository|EntityRepository The repository class.

bool contains(object $entity)

Determines whether an entity instance is managed in this EntityManager.

Parameters

object $entity

Return Value

bool TRUE if this EntityManager currently manages the given entity, FALSE otherwise.

EventManager getEventManager()

Gets the EventManager used by the EntityManager.

Return Value

EventManager

Configuration getConfiguration()

Gets the Configuration used by the EntityManager.

Return Value

Configuration

bool isOpen()

Check if the Entity manager is open or closed.

Return Value

bool

UnitOfWork getUnitOfWork()

Gets the UnitOfWork used by the EntityManager to coordinate operations.

Return Value

UnitOfWork

AbstractHydrator getHydrator(int $hydrationMode)

Gets a hydrator for the given hydration mode.

This method caches the hydrator instances which is used for all queries that don't selectively iterate over the result.

Parameters

int $hydrationMode

Return Value

AbstractHydrator

AbstractHydrator newHydrator(int $hydrationMode)

Create a new instance for the given hydration mode.

Parameters

int $hydrationMode

Return Value

AbstractHydrator

Exceptions

ORMException

ProxyFactory getProxyFactory()

Gets the proxy factory used by the EntityManager to create entity proxies.

Return Value

ProxyFactory

initializeObject($obj)

{@inheritDoc}

Parameters

$obj

static EntityManager create(Connection|mixed[] $connection, Configuration $config, EventManager|null $eventManager = null)

Factory method to create EntityManager instances.

Parameters

Connection|mixed[] $connection An array with the connection parameters or an existing Connection instance.
Configuration $config The Configuration instance to use.
EventManager|null $eventManager The EventManager instance to use.

Return Value

EntityManager The created EntityManager.

Exceptions

InvalidArgumentException
ORMException

static protected Connection createConnection(Connection|mixed[] $connection, Configuration $config, EventManager|null $eventManager = null)

Factory method to create Connection instances.

Parameters

Connection|mixed[] $connection An array with the connection parameters or an existing Connection instance.
Configuration $config The Configuration instance to use.
EventManager|null $eventManager The EventManager instance to use.

Return Value

Connection

Exceptions

InvalidArgumentException
ORMException

FilterCollection getFilters()

Gets the enabled filters.

Return Value

FilterCollection The active filter collection.

bool isFiltersStateClean()

Checks whether the state of the filter collection is clean.

Return Value

bool True, if the filter collection is clean.

bool hasFilters()

Checks whether the Entity Manager has filters.

Return Value

bool True, if the EM has a filter collection.