Search code examples
phpsymfonydynamiccallgetter

Calling all the getters from an entity


After using:

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

I have an array of entities for which I want to use all their property getters. I'm doing this like this:

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));
}

The letter used in SetCellValue function will also increase. I'm putting this as an example. Is there a way to dynamically call all the getters of the entity, so I don't have to call them one by one? Something like this for example:

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

Solution

  • This is a PHP-general answer which should work in your case. Try this:

    <?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);
    

    Given any plain old PHP object, you can use get_class_methods() to get a list of all methods on an object that are visible in the scope where get_class_methods() is called - in this case all public methods.

    Then we filter over this array of values and only return the getters.

    For the above example, this yields:

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

    Now you can call your getters dynamically, like so:

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

    Hope this helps :)