繁体   English   中英

从 Doctrine 获取实体数组/列表

[英]Get array/list of entities from Doctrine

这可能很简单,但我找不到办法做到这一点。

有没有办法获得 Doctrine 管理的实体的类名列表? 就像是:

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

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

我知道这个问题很老,但以防万一有人仍然需要这样做(在 Doctrine 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”和“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;
}

请注意,为了简单起见,我上面的代码示例没有使用命名空间。 您必须在您的应用程序中相应地调整它。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM