Get entity name from class object

后端 未结 4 826
予麋鹿
予麋鹿 2021-01-17 08:23

I have the following code:

namespace Acme\\StoreBundle\\Entity;

use Doctrine\\ORM\\Mapping as ORM;

/**
 * Acme\\StoreBundle\\Entity\\User
 *
 * @ORM\\Tabl         


        
相关标签:
4条回答
  • 2021-01-17 08:57

    PHP get_class() function will return User and namespace (see comments in php docs).

    0 讨论(0)
  • 2021-01-17 08:57

    getClassMetadata() is deprecated and will be removed in the future. Use getMetadataFor() instead:

    $entityName = $this->em->getMetadataFactory()->getMetadataFor(get_class($entity))->getName();
    

    Or a complete function:

    /**
     * Returns Doctrine entity name
     *
     * @param mixed $entity
     *
     * @return string
     * @throws \Exception
     */
    private function getEntityName($entity)
    {
        try {
            $entityName = $this->em->getMetadataFactory()->getMetadataFor(get_class($entity))->getName();
        } catch (MappingException $e) {
            throw new \Exception('Given object ' . get_class($entity) . ' is not a Doctrine Entity. ');
        }
    
        return $entityName;
    }
    
    0 讨论(0)
  • 2021-01-17 08:58

    This should always work (no return of Proxy class):

    $em = $this->container->get('doctrine')->getEntityManager(); 
    $className = $em->getClassMetadata(get_class($object))->getName();
    

    As getClassMetadata is deprecated, you can now use getMetadataFor

    $entityName = $this->em->getMetadataFactory()->getMetadataFor(get_class($object))->getName();
    
    0 讨论(0)
  • 2021-01-17 08:58

    You can use php's instanceOf operator:

    if($a instanceof MyClass) { /*code*/ }
    

    https://www.php.net/manual/pt_BR/language.operators.type.php

    0 讨论(0)
提交回复
热议问题