Embeddables allow you to wrap multiple properties into a single, reusable data class that is embedded within an entity. This helps separate concerns and promotes immutable design.
To create an embeddable:
- Inherit from
Nextras\Orm\Entity\Embeddable\Embeddable. - Define properties using PHPDoc
@property tags. - In the parent Entity, declare the embeddable property using the
{embeddable} PHPDoc tag.
Note on Nullability: If all properties within an embeddable are null, Orm will not instantiate the embeddable object and will instead set the entity's property to null. The nullability of the embeddable and its properties is derived from your PHPDoc types.
Note on Updating: Embeddables are immutable by design. To change a value within an embeddable, you must create a new instance of the embeddable class and assign it to the entity property.
/**
* @property Address|null $address {embeddable}
*/
class User extends Nextras\Orm\Entity\Entity
{
}
/**
* @property string $street
* @property string $city
* @property string|null $state
* @property string $country
* @property string $zipCode
*/
class Address extends Nextras\Orm\Entity\Embeddable
{
public function __construct(string $street, string $city, ?string $state, string $country, string $zipCode)
{
parent::__construct([
'street' => $street,
'city' => $city,
'state' => $state,
'country' => $country,
'zipCode' => $zipCode,
]);
}
}
// Usage:
$user = new User();
$user->address = new Address('Main st.', 'Prague', null, 'Czechia', '10000');
echo $user->address->street;