简体   繁体   English

从 Doctrine 获取实体数组/列表

[英]Get array/list of entities from Doctrine

This is probably pretty simple, but I can't find a way to do this.这可能很简单,但我找不到办法做到这一点。

Is there any way to get a list of class names of the entities that Doctrine manages?有没有办法获得 Doctrine 管理的实体的类名列表? Something like:就像是:

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

where $entities is an array with something like array('User', 'Address', 'PhoneNumber') etc...其中$entities是一个数组,类似于array('User', 'Address', 'PhoneNumber')等...

I know this question is old, but in case someone still needs to do it (tested in Doctrine 2.4.0):我知道这个问题很老,但以防万一有人仍然需要这样做(在 Doctrine 2.4.0 中测试):

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

Source来源

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

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

Unfortunately not, your classes should be organized in the file structure though.不幸的是,您的类应该在文件结构中组织。 Example: a project i'm working on now has all its doctrine classes in an init/classes folder.示例:我现在正在处理的一个项目在 init/classes 文件夹中包含所有的学说类。

There is no built function.没有内置功能。 But you can use marker/tagger interface to tag entity classes that belong to your application.但是您可以使用标记/标记器接口来标记属于您的应用程序的实体类。 You can then use the functions "get_declared_classes" and "is_subclass_of" find the list of entity classes.然后您可以使用函数“get_declared_classes”和“is_subclass_of”查找实体类列表。

For ex:例如:

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

Please note that my code sample above does not use namespaces for the sake simplicity.请注意,为了简单起见,我上面的代码示例没有使用命名空间。 You will have to adjust it accordingly in your application.您必须在您的应用程序中相应地调整它。

That said you did't explain why you need to find the list of entity classes.也就是说,您没有解释为什么需要查找实体类列表。 Perhaps, there is a better solution for what your are trying to solve.也许,对于您要解决的问题,有更好的解决方案。

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

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