FloydThreepwood
FloydThreepwood

Reputation: 1585

How does Doctrine2 set the Id values

I have a question out of curiosity about the inner workings of Doctrine2. I as a User see a really clean and robust interface, but there must be some heavy magic at work under the hood.

When I generate a simple entity it looks something like this:

class SimpleEntity
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string")
     */
    protected $title;

    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set title
     *
     * @param string $title
     */
    public function setTitle($title)
    {
        $this->title = $title;
    }

    /**
     * Get title
     *
     * @return string 
     */
    public function getTitle()
    {
        return $this->title;
    }
}

As you will notice one thing is conspicuously absent, there is no way to set the id, but nevertheless doctrines factories return entities with set ids. How can that work? I have tried to look through the source, but lost the track somewhere.

How can it be possible to overwrite protected values without being in the class hierarchy?

Upvotes: 1

Views: 619

Answers (1)

Phil
Phil

Reputation: 164834

The answer is Reflection. See http://www.doctrine-project.org/docs/orm/2.1/en/tutorials/getting-started-xml-edition.html#a-first-prototype

Without digging into the Doctrine source, I'd say it makes use of ReflectionProperty::setValue()

Upvotes: 4

Related Questions