Doctrine\ORM\UnitOfWork::lock PHP Method

lock() public method

Acquire a lock on the given entity.
public lock ( object $entity, integer $lockMode, integer $lockVersion = null )
$entity object
$lockMode integer
$lockVersion integer
    public function lock($entity, $lockMode, $lockVersion = null)
    {
        if ($this->getEntityState($entity) != self::STATE_MANAGED) {
            throw new InvalidArgumentException("Entity is not MANAGED.");
        }
        
        $entityName = get_class($entity);
        $class = $this->em->getClassMetadata($entityName);

        if ($lockMode == \Doctrine\DBAL\LockMode::OPTIMISTIC) {
            if (!$class->isVersioned) {
                throw OptimisticLockException::notVersioned($entityName);
            }

            if ($lockVersion != null) {
                $entityVersion = $class->reflFields[$class->versionField]->getValue($entity);
                if ($entityVersion != $lockVersion) {
                    throw OptimisticLockException::lockFailedVersionMissmatch($entity, $lockVersion, $entityVersion);
                }
            }
        } else if (in_array($lockMode, array(\Doctrine\DBAL\LockMode::PESSIMISTIC_READ, \Doctrine\DBAL\LockMode::PESSIMISTIC_WRITE))) {

            if (!$this->em->getConnection()->isTransactionActive()) {
                throw TransactionRequiredException::transactionRequired();
            }
            
            $oid = spl_object_hash($entity);

            $this->getEntityPersister($class->name)->lock(
                array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]),
                $lockMode
            );
        }
    }

Usage Example

Example #1
0
 /**
  * {@inheritDoc}
  */
 public function lock($entity, $lockMode, $lockVersion = null)
 {
     $this->unitOfWork->lock($entity, $lockMode, $lockVersion);
 }