【问题标题】:Get array/list of entities from Doctrine从 Doctrine 获取实体的数组/列表
【发布时间】:2013-02-22 19:11:50
【问题描述】:

这可能很简单,但我找不到方法。

有什么方法可以获取 Doctrine 管理的实体的类名列表?比如:

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

其中$entities 是一个包含array('User', 'Address', 'PhoneNumber') 等内容的数组...

【问题讨论】:

    标签: php database doctrine entities


    【解决方案1】:

    我知道这个问题很老了,但如果有人仍然需要这样做(在 Doctrine 2.4.0 中测试):

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

    Source

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        很遗憾,您的类应该按文件结构组织。示例:我正在处理的一个项目现在在 init/classes 文件夹中包含其所有学说类。

        【讨论】:

        • 是的,它们都在一个文件夹中。我只是希望有一个像这样的简单方法。我想我可以将它添加进去,然后看看我的实体文件夹。
        • print_r(get_declared_classes());会给你一个脚本中使用的类的列表,但它不限于你的学说类。编辑:它也不包括子子类,只包括类及其子类。
        【解决方案4】:

        没有内置函数。但是您可以使用marker/tagger interface 来标记属于您的应用程序的实体类。然后可以使用“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;
        }
        

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-12-23
          • 1970-01-01
          • 1970-01-01
          • 2014-06-06
          • 2013-06-20
          相关资源
          最近更新 更多