Search code examples
symfonysymfony-3.4

Symfony 3.4: Set multiple properties for entity?


I can create a new entity and add its data like this:

$foo = new Foo();
$foo->setName('Abc');
$foo->setYear('1994');

This is using the setter methods that I've defined in my entity class.

However, let's assume that I have this array:

$array = array('name' => 'Abc', 'year' => '1994');

Is there a way for me to do this:

$foo->setData($data);

Ideally all the individual array entries should be added to the entity, just like in my first example where I did it manually.


Solution

  • it's ugly but, in the foo class:

    function setData(array $data) {
        foreach($data as $key => $value) {
            $this->$key = $value;
        }
    }
    

    this obivously circumvents the setter logic, so

    function setData(array $data) {
        foreach($data as $key => $value) {
            $func = 'set'.ucfirst($key);
            $this->$func($value);
        }
    }
    

    you might even write some global

    function setDataOnObject(array $data, object $object) {
        foreach($data as $key => $value) {
            $func = 'set'.ucfirst($key);
            $object->$func($value);
        }
    }
    

    this obviously all requires, that the setters actually exist...

    you could also use the serializer component as enricog suggested in their comment. Or you could use the property access component, which will by itself find the right setters or adders.