1

Is it possible with Doctrine2 to use a method which creates an entity out of an array?

I mean somehow Doctrine2 converts the database return values to objects. Including children.

If it is possible a link and en example would be very helpful. Thanks.

1
  • 1
    Nothing built in since doctrine entities as just plain objects. But you could certainly make your own factory. Commented May 26, 2015 at 22:33

1 Answer 1

1

Doctrine's DBAL and ORM layers are just abstractions over PDO. When specifying PDO::FETCH_CLASS as the fetch_argument, the PDOStatement::fetchAll() method will fetch the returned result set into the specified class.

See Example #4 Instantiating a class for each result in the docs for further information.

I assume that this is what Doctrine2 does under the hood, and as such it's a PDO feature, not a Doctrine2 feature.

As Cerad pointed out in the comment above, since Doctrine2 Entities are just POPOs, you'd have to perhaps create a factory, pass data into a constructor or some other method to fill your entity from an array.

I've done something similar to the following in the past:

<?php

class State
{
    private $name;

    private $abbreviation;

    public function fromArray(array $data)
    {
        foreach ($data as $prop => $value) {
            if (!property_exists($this, $prop)) {
                throw new UnexpectedValueException(
                    sprintf('Property %s does not exist in State', $prop)
                );
            }

            $this->{$prop} = $value;
        }
    }
}

$state = new State();
$state->fromArray([
    'name' => 'Arizona',
    'abbreviation' => 'AZ',
]);

var_dump($state);

This yields:

object(State)#1 (2) {
  ["name":"State":private]=>
  string(7) "Arizona"
  ["abbreviation":"State":private]=>
  string(2) "AZ"
}

Hope this helps :)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.