Doctrine\ODM\MongoDB\UnitOfWork::tryGetById PHP Method

tryGetById() public method

INTERNAL: Tries to get a document by its identifier hash. If no document is found for the given hash, FALSE is returned.
public tryGetById ( mixed $id, ClassMetadata $class ) : mixed
$id mixed Document identifier
$class Doctrine\ODM\MongoDB\Mapping\ClassMetadata Document class
return mixed The found document or FALSE.
    public function tryGetById($id, ClassMetadata $class)
    {
        if (!$class->identifier) {
            throw new \InvalidArgumentException(sprintf('Class "%s" does not have an identifier', $class->name));
        }
        $serializedId = serialize($class->getDatabaseIdentifierValue($id));
        return isset($this->identityMap[$class->name][$serializedId]) ? $this->identityMap[$class->name][$serializedId] : false;
    }

Usage Example

 /**
  * Finds a document by its identifier
  *
  * @throws LockException
  * @param string|object $id The identifier
  * @param int $lockMode
  * @param int $lockVersion
  * @return object The document.
  */
 public function find($id, $lockMode = LockMode::NONE, $lockVersion = null)
 {
     if ($id === null) {
         return;
     }
     if (is_array($id)) {
         list($identifierFieldName) = $this->class->getIdentifierFieldNames();
         if (!isset($id[$identifierFieldName])) {
             throw MongoDBException::missingIdentifierField($this->documentName, $identifierFieldName);
         }
         $id = $id[$identifierFieldName];
     }
     // Check identity map first
     if ($document = $this->uow->tryGetById($id, $this->class->rootDocumentName)) {
         if ($lockMode != LockMode::NONE) {
             $this->dm->lock($document, $lockMode, $lockVersion);
         }
         return $document;
         // Hit!
     }
     if ($lockMode == LockMode::NONE) {
         return $this->uow->getDocumentPersister($this->documentName)->load($id);
     } else {
         if ($lockMode == LockMode::OPTIMISTIC) {
             if (!$this->class->isVersioned) {
                 throw LockException::notVersioned($this->documentName);
             }
             $document = $this->uow->getDocumentPersister($this->documentName)->load($id);
             $this->uow->lock($document, $lockMode, $lockVersion);
             return $document;
         } else {
             return $this->uow->getDocumentPersister($this->documentName)->load($id, null, array(), $lockMode);
         }
     }
 }
All Usage Examples Of Doctrine\ODM\MongoDB\UnitOfWork::tryGetById
UnitOfWork