Nullable Embeddable with Symfony and Doctrine ORM
Let’s say you have a Symfony entity Person
with a Doctrine ORM Embeddable EmailAddress
value object:
This works without a problem at first sight. You create a migration, the email_address
field is added as nullable to your person
table and everything looks fine.
The problem appears when you save the entity without an email address (set the property to null
) and then use this entity somewhere again.
What happens then is that Doctrine ORM hydrates the Person
object for you, but when you take a look at the $emailAddress
property you won’t get null
here, but an “empty” EmailAddress
object:
This is not a useful object to work with.
So, how can we solve this in the most elegant way, as Doctrine won’t support this kind of nullable objects for Embeddable in the near future?
Doctrine ORM lifecycle events to the rescue!
We create two interfaces in our domain layer:
We mark our value object (with an interface) as nullable Embeddable:
and the Person
entity as container for such an Embeddable (again with an interface):
Finally we add the event subscriber to listen for the Doctrine ORM postLoad
lifecycle event:
which sets the property itself to null
if all the NullableEmbeddable
properties are null
.
hth