symfony 从类对象获取实体名称

btxsgosb  于 2023-03-19  发布在  其他
关注(0)|答案(5)|浏览(156)

下面的代码:

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();

有人知道现在如何从User对象中获取实体名称(AcmeStoreBundle:User)吗?

rekjcdws

rekjcdws1#

这应该始终有效(不返回Proxy类):

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

由于getClassMetadata已弃用,您现在可以使用getMetadataFor

$entityName = $this->em->getMetadataFactory()->getMetadataFor(get_class($object))->getName();
643ylb08

643ylb082#

getClassMetadata()已弃用,将来将被删除。请改用getMetadataFor():

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

或完整功能:

/**
 * 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;
}
whitzsjs

whitzsjs3#

PHP get_class()函数将返回User和名称空间(参见php文档中的注解)。

jucafojl

jucafojl4#

你可以使用php的instanceOf操作符:

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

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

pzfprimi

pzfprimi5#

如果只需要类名:

private function getEntityClassName(object $entity): string
{
    return $this->entityManager->getMetadataFactory()>getMetadataFor(
        $entity::class
    )->getReflectionClass()->getShortName();
}

相关问题