'How to check if a class is a Doctrine entity?
Given a class name, say Domain\Model\User, is there a programmatic way to know whether this class is marked as a Doctrine entity?
I could check for the presence of the @Entity annotation, but I'm looking for a generic way that would work with any metadata driver (annotations, YAML, XML, etc.)
Solution 1:[1]
As an addition to Benjamin his answer...
If you know for sure that you are handling doctrine entities, but you are not sure whether you have a proxy or a instance of the real class you can easily retrieve the real class by using the Doctrine Common ClassUtils:
use Doctrine\Common\Util\ClassUtils;
and then you can get the real class through the static getClass method like this:
$proxyOrEntity;
$className = ClassUtils::getClass($proxyOrEntity);
So this means @Benjamin his isEntity function can be written like this:
/**
* @param EntityManager $em
* @param string|object $class
*
* @return boolean
*/
function isEntity(EntityManager $em, $class)
{
if(is_object($class)){
$class = ClassUtils::getClass($class);
}
return ! $em->getMetadataFactory()->isTransient($class);
}
Which will give you true/false depending on whether the class is a doctrine entity or not.
Solution 2:[2]
One work around would be to test if you can generate a Repository. This is 'bullet proof' in that it will fail if the current schema and mapping does not know about the object class in question.
// Get the entity manager. I don't know how you do it
$em = new Doctrine\ORM\EntityManager();
try {
$repo = $em->getRepository('YourClassModel');
} catch (Doctrine\Common\Persistence\Mapping\MappingException $e) {
// NOPE! Not a mapped model
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Rottingham |
