Mapping Entity Identity

Our Identity, OrderId, is a Value Object. As seen in the previous chapter, there are different approaches for mapping a Value Object using Doctrine, embeddables, and custom types. When Value Objects are used as Identities, the best option is custom types.

An interesting new feature in Doctrine 2.5 is that it's now possible to use Objects as identifiers for Entities, so long as they implement the magic method __toString(). So we can add  __toString to our Identity Value Objects and use them in our mappings:

namespace DddBillingDomainModelOrder;

use RamseyUuidUuid;

class OrderId
{
// ...

public function __toString()
{
return $this->id;
}
}

Check the implementation of the Doctrine custom types. They inherit from GuidType, so their internal representation will be a UUID. We need to specify the database native translation. Then we need to register our custom types before we use them. If you need help with these steps, Custom Mapping Types is a good reference.

use DoctrineDBALPlatformsAbstractPlatform;
use DoctrineDBALTypesGuidType;

class DoctrineOrderId extends GuidType
{
public function getName()
{
return 'OrderId';
}

public function convertToDatabaseValue(
$value, AbstractPlatform $platform
) {
return $value->id();
}

public function convertToPHPValue(
$value, AbstractPlatform $platform
) {
return new OrderId($value);
}
}

Lastly, we'll set up the registration of custom types. Again, we have to update our bootstrapping:

require_once '/path/to/vendor/autoload.php';

// ...

DoctrineDBALTypesType::addType(
'OrderId',
'DddBillingInfrastructureDomainModelDoctrineOrderId'
);

$config = Setup::createXMLMetadataConfiguration($paths, $isDevMode);
$entityManager = EntityManager::create($dbParams, $config);
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset