7

I would like to call a getter with the stored fieldname from the database.

For example, there are some fieldnames store like ['id','email','name'].

$array=Array('id','email','name');

Normally, I will call ->getId() or ->getEmail()....

In this case, I have no chance to handle things like this. Is there any possibility to get the variable as part of the get Command like...

foreach ($array as $item){
   $value[]=$repository->get$item();
}

Can I use the magic Method in someway? this is a bit confusing....

Guillaume Fache
  • 813
  • 10
  • 21
TheTom
  • 934
  • 2
  • 14
  • 40

3 Answers3

8

Symfony offers a special PropertyAccessor you could use:

use Symfony\Component\PropertyAccess\PropertyAccess;

$accessor = PropertyAccess::createPropertyAccessor();

class Person
{
    private $firstName = 'Wouter';

    public function getFirstName()
    {
        return $this->firstName;
    }
}

$person = new Person();

var_dump($accessor->getValue($person, 'first_name')); // 'Wouter'

http://symfony.com/doc/current/components/property_access/introduction.html#using-getters

althaus
  • 2,009
  • 2
  • 25
  • 33
  • Sorry Guys, but is there also a possibility to use this for setters? $new= new Whatever(); And then use a setter for all data which will come in? – TheTom Jul 28 '15 at 13:54
  • @TheTom Check the linked doc. It's documented how to write to objects. – althaus Jul 28 '15 at 14:41
4

You can do it like this :

// For example, to get getId()
$reflectionMethod = new ReflectionMethod('AppBundle\Entity\YourEntity','get'.$soft[0]);
$i[] = $reflectionMethod->invoke($yourObject);

With $yourObject being the object of which you want to get the id from.

EDIT : Don't forget the use to add :

use ReflectionMethod;

Hope this helps.

Guillaume Fache
  • 813
  • 10
  • 21
  • Oh this is quite nice! Do I need to add any use statements? For the reason, symfony says "Attempted to load class "ReflectionMethod" from namespace "DatacareBundle\Controller". Did you forget a "use" statement for another namespace? " – TheTom Jun 30 '15 at 15:04
  • ok I found it. there was a missing \ : $reflectionMethod = new \ReflectionMethod(...// – TheTom Jun 30 '15 at 15:14
1
<?php
// You can get Getter method like this
use Doctrine\Common\Inflector\Inflector;

$array = ['id', 'email', 'name'];
$value = [];

foreach ($array as $item){
    $method = Inflector::classify('get_'.$item);
    // Call it
    if (method_exists($repository, $method))
        $value[] = $repository->$method();
}
Hazem Noor
  • 176
  • 3
  • 8