If you’re developing applications in a Domain-Driven Design style and using Doctrine 2.5, you may be struggling with implementing your entities identities, I mean, UserId, ProductId, and so on. Embeddables are cool, but limited. Surrogates are not necessary anymore. Here are some short tips and examples about how to proceed.
If using Doctrine 2.5, embeddables are not an option yet for implementing your identities. The best option is using Custom Types.
What’s new in Doctrine 2.5
An interesting new feature about Doctrine 2.5, is that now, it’s possible to use Objects as identifiers for Entities as long as they implement the magic method <span class="pre">__toString()</span>. So we can add __toString to our Identities Value Objects and use them in our mappings. Let’s see.
Consider the context of Last Wishes. To sum up, users that have wishes. Users are identified by a UserId, a value object that holds a UUID. Wishes are identified by a WishId and have a reference to its owner, a UserId.
Our Identity VO
First of all, let’s see our current identity objects. Remember, we need to add the __toString() method. First, UserId.
Check the implementation of the Doctrine Custom Types. They inherit from GuidType, so their internal representation will be an UUID. We need to specify what’s the database back and forward conversion. Last, we need to register our custom types before use them.
First, a base type for the UserId and WishId custom types.
Now, the UserId custom type.
Time for the WishId custom type.
Last, custom types registration.
Check now Doctrine mappings. See how we’re using our custom types in the “type” field.
Hope it helps to all the DDD lovers!