从条令中获取实体数组/列表


Get array/list of entities from Doctrine

这可能很简单,但我找不到实现这一点的方法。

有什么方法可以得到Doctrine管理的实体的类名列表吗?类似于:

$entities = $doctrine->em->getEntities();

其中$entities是一个类似于array('User', 'Address', 'PhoneNumber')等的数组…

我知道这个问题已经过时了,但如果有人仍然需要这样做(在条令2.4.0中测试):

$classes = array();
$metas = $entityManager->getMetadataFactory()->getAllMetadata();
foreach ($metas as $meta) {
    $classes[] = $meta->getName();
}
var_dump($classes);

获取所有实体(带命名空间)类名的另一种方法是:

$entitiesClassNames = $entityManager->getConfiguration()->getMetadataDriverImpl()->getAllClassNames();

不幸的是,您的类应该按照文件结构进行组织。示例:我现在正在处理的一个项目将其所有的条令类都放在init/classes文件夹中。

没有构建函数。但是您可以使用标记器/标记器接口来标记属于您的应用程序的实体类。然后,您可以使用函数"get_declared_classes"answers"is_subclass_of"来查找实体类的列表。

例如:

/**
 * Provides a marker interface to identify entity classes related to the application
 */
interface MyApplicationEntity {}
/**
 * @Entity
 */
class User implements MyApplicationEntity {
   // Your entity class definition goes here.
}
/**
 * Finds the list of entity classes. Please note that only entity classes
 * that are currently loaded will be detected by this method.
 * For ex: require_once('User.php'); or use User; must have been called somewhere
 * within the current execution.
 * @return array of entity classes.
 */
function getApplicationEntities() {
    $classes = array();
    foreach(get_declared_classes() as $class) {
        if (is_subclass_of($class, "MyApplicationEntity")) {
            $classes[] = $class;
        }
    }
    return $classes;
}

请注意,为了简单起见,我上面的代码示例没有使用名称空间。您必须在申请中对其进行相应调整。

也就是说,您没有解释为什么需要查找实体类的列表。也许,对于你试图解决的问题,有一个更好的解决方案。