2015-08-20 41 views
-2

調用所有的干將使用後:
從實體

$queryResult = 
    $this 
     ->getDoctrine() 
     ->getRepository('EtecsaAppBundle:Paralizacion') 
     ->createQueryBuilder('e') 
     ->getQuery(); 
     ->setDQL($myOwnQuery) 
     ->getResult(); 

我有,我想用自己的全部財產的getter實體的數組。我這樣做是這樣的:

foreach ($queryResult as $index => $itemEntity) 
{ 
    $objWorksheet->SetCellValue('A'. ($index + 17), $index + 1); 
    // ... The itemEntity class has entity relationships associations 
    $objWorksheet->SetCellValue('B'. ($index + 17), $itemEntity->getSomeRelatedProperty()->getSomeProperty()); 
    // ... it also has properties with several types (date, string, etc) 
    $objWorksheet->SetCellValue('C'. ($index + 17), $itemEntity->getSomeProperty)); 
    // Also some of the values obtained from his respective getter require some processing 
    $objWorksheet->SetCellValue('D'. ($index + 17), getProcessedValue($itemEntity->getSomeSpecificProperty)); 
} 

在SetCellValue函數中使用的字母也會增加。我以此爲例。 有沒有辦法動態調用實體的所有getter,所以我不必一個一個的打電話給他們?這樣的例如:

foreach ($queryResult as $index => $itemEntity) 
{ 
    $columnLetter = 'A'; 
    $objWorksheet->SetCellValue($columnLetter++ . ($index + 17), $index + 1); 

    arrayOfGetters = getArrayOfGetters(itemEntity); 
    foreach (arrayOfGetters as $getterMethod) 
    { 
     // properties that reference an entity relationship association would have the __ToString function 
     $objWorksheet->SetCellValue($columnLetter++ . ($index + 17), /* get value of getterMethod */); 
    } 
} 
+0

而問題是什麼? –

+0

@JovanPerovic 對不起......我要求一種方式來動態調用實體的所有獲取者,所以我不必一一給他們打電話 –

+0

我認爲人們對你的問題投下了一票,因爲它是有些模糊。我認爲你的問題的癥結在於標題(因此我提交了答案),但是下面的內容「SetCellValue函數中使用的字母也會增加」問題的一部分?如果是這樣,請澄清,我會盡力相應地更新我的答案。 –

回答

1

這是一個PHP的一般性的答案應該在你的情況下工作。試試這個:

<?php 

class Entity 
{ 
    public function setFoo($foo) 
    { 
     $this->foo = $foo; 
    } 

    public function getFoo() 
    { 
     return $this->foo; 
    } 
} 


$entity = new Entity(); 
$entity->setFoo('foo!'); 

$getters = array_filter(get_class_methods($entity), function($method) { 
    return 'get' === substr($method, 0, 3); 
}); 

var_dump($getters); 

鑑於任何普通的舊的PHP對象,你可以使用get_class_methods()得到的是在get_class_methods()被稱爲範圍是可見的對象上的所有方法的列表 - 在這種情況下,所有public方法。

然後我們過濾這個值的數組,然後只返回getters。

對於上面的例子,這產生了:

array(1) { 
    [1] => 
    string(6) "getFoo" 
} 

現在你可以打電話給你的干將動態,就像這樣:

foreach ($getters as $getter) { 
    echo $entity->{$getter}(); // `foo!` 
} 

希望這有助於:)

+0

有一點需要注意:afaik,'get_class_methods()'也會返回靜態方法的名字。可能不是你的情況,因爲你不可能有靜態的getter和setter。但值得指出! –

+0

有一個問題@Darragh我在哪裏可以得到一些有關在這個'$ entity - > {$ getter}()'{ –

+0

}上使用的信息嗨,實際上,在這種情況下它是完全多餘的,所以你可以使用'$實體 - > $ getter()'代替。我實際上將它編輯出來,但後來我發現它可能說明您可以使用字符串值作爲對象的可調用佔位符。有時候人們看不到' - > $':) –