Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine: extending entity class

Tags:

php

orm

doctrine

I would like to extend Entity\Base classes, how to do this in Doctrine 2.1? My research showed that whenever someone encounters the problem with doing this he switches to Doctrine 1.2 :)n I am using yaml configuration

like image 613
mkk Avatar asked Jan 20 '12 15:01

mkk


2 Answers

Doctrine 2.X Entities work as POPOs (Plain Old PHP Objects). To achieve extending correctly, Doctrine enforces you to use a concept from JPA called Mapped Super Classes. The idea is pretty simple. Whenever you want to have a base class and want your entities to extend from it (I'm not talking about inheritance at DB level), all you need to do is create your Base class as a MappedSuperClass.

Here is an example: http://www.doctrine-project.org/docs/orm/2.1/en/reference/inheritance-mapping.html#mapped-superclasses

Thanks

like image 127
Guilherme Blanco Avatar answered Oct 05 '22 22:10

Guilherme Blanco


Here the solution from Guilherme Blanco link. I like to have a posted solution instead of a link which eventually could no longer work in future:

<?php
/** @MappedSuperclass */
class MappedSuperclassBase
{
    /** @Column(type="integer") */
    protected $mapped1;

    /** @Column(type="string") */
    protected $mapped2;

    /**
     * @OneToOne(targetEntity="MappedSuperclassRelated1")
     * @JoinColumn(name="related1_id", referencedColumnName="id")
     */
    protected $mappedRelated1;

    // ... more fields and methods
}

/** @Entity */
class EntitySubClass extends MappedSuperclassBase
{
    /** @Id @Column(type="integer") */
    private $id;

    /** @Column(type="string") */
    private $name;

    // ... more fields and methods
}
like image 43
0xPixelfrost Avatar answered Oct 06 '22 00:10

0xPixelfrost