I need move some immutable fields into separate class, but I don't really want to use "join", because I need all data together every time.
Is any way to have some entity attributes as classes that mapped into same table?
Something like:
/**
* @ORM\Entity
*/
class User {
/**
* @var int
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
...
/**
* @var Address
* @ORM\... ??
*/
protected $address
}
/**
* @ORM\ValueObject ??
*/
class Address {
/**
* @var string
* @ORM\Column(type="string", name="address_zipcode", length=12)
*/
protected $zipcode;
/**
* @var string
* @ORM\Column(type="string", name="address_country_iso", length=3)
*/
protected $countryIso;
...
}
And table structure would be:
CREATE TABLE User (
`id` INT(11) NOT NULL auto_increment,
`address_zipcode` VARCHAR(12) NOT NULL,
`address_country_iso` VARCHAR(3) NOT NULL,
PRIMARY KEY (`id`)
);
Doctrine introduced the concept of value objects in version 2.x
.
The name for new attributes/annotations are Embeddable
and Embedded
. The first for mark the Value Object class, and the second for actual injecting Value Object into the parent Entity.
Here is updated code snippet from my original question:
/** @ORM\Entity */
class User {
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
...
/** @ORM\Embedded(class="Address", columnPrefix="address") */
protected $address
}
/** @ORM\Embeddable */
class Address {
/** @ORM\Column(type="string", name="address_zipcode", length=12) */
protected $zipcode;
/** @ORM\Column(type="string", name="address_country_iso", length=3) */
protected $countryIso;
...
}
Resources: