Get entity name from class object

2019-02-21 07:46发布

I have the following code:

namespace Acme\StoreBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Acme\StoreBundle\Entity\User
 *
 * @ORM\Table(name="users")
 * @ORM\Entity()
 */
class User {
...
}

$user = new User();

Does anybody know how I can now get the entity name (AcmeStoreBundle:User) from the User object?

3条回答
疯言疯语
2楼-- · 2019-02-21 08:18

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();
查看更多
Ridiculous、
3楼-- · 2019-02-21 08:31

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

查看更多
Emotional °昔
4楼-- · 2019-02-21 08:36

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;
}
查看更多
登录 后发表回答