2013-02-22 103 views
2

這可能很簡單,但我找不到這樣做的方法。從Doctrine獲取數組/實體列表

有什麼辦法可以獲得Doctrine管理的實體類名列表?喜歡的東西:

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

其中$entities是像array('User', 'Address', 'PhoneNumber')等數組...

回答

0

不幸的是沒有,你的類應該在文件結構雖然組織。例如:我正在處理的一個項目的所有教義類都放在init/classes文件夾中。

+0

是的,他們都是一個文件夾中。我只是希望能有這樣一個簡單的方法。我想我可以添加它,並只需要查看我的實體文件夾。 – celestialorb 2013-02-22 19:24:04

+0

print_r(get_declared_classes());會給你一個腳本中使用的類的列表,但它不會限於你的教義類。編輯:它也不會包含子子類,只有類和它們的子類。 – skrilled 2013-02-22 20:02:22

1

沒有構建函數。但是您可以使用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; 
} 

請注意,我的代碼示例中沒有使用的命名空間爲求簡單。你將不得不在你的應用程序中相應地調整它。

這就是說你沒有解釋爲什麼你需要找到實體類的列表。也許,對於你正在努力解決的問題,有一個更好的解決方案。

14

我知道這個問題是舊的,但如果有人仍然需要做(在教義2.4.0測試):

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

Source