11

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? Something like:

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

where $entities is an array with something like array('User', 'Address', 'PhoneNumber') etc...

celestialorb
  • 1,901
  • 7
  • 29
  • 50

4 Answers4

36

I know this question is old, but in case someone still needs to do it (tested in Doctrine 2.4.0):

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

Source

Jack Sleight
  • 17,010
  • 6
  • 41
  • 55
5

Another way to get the class names of all entities (with namespace) is:

$entitiesClassNames = $entityManager->getConfiguration()->getMetadataDriverImpl()->getAllClassNames();
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Hubert Dziubiński
  • 1,386
  • 1
  • 11
  • 5
0

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.

skrilled
  • 5,350
  • 2
  • 26
  • 48
  • Yes, they are all in one folder. I was just hoping there would be a simple method like this. I suppose I could add it in and have it just take a peek into my entities folder. – celestialorb Feb 22 '13 at 19:24
  • print_r(get_declared_classes()); will give you a list of classes used in a script, but it will not be limited to your doctrine classes. edit: it also won't include sub-sub-classes, only classes and their subclasses. – skrilled Feb 22 '13 at 20:02
0

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.

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.