Doctrine Custom Mapping Types

As our Post Entity is composed of Value Objects like Body or PostId, it's a good idea to make Custom Mapping Types or use Doctrine Embeddables for them, as seen in the Value Objects chapter. This will make the object mapping considerably easier:

namespace InfrastructurePersistenceDoctrineTypes;

use DoctrineDBALTypesType;
use DoctrineDBALPlatformsAbstractPlatform;
use DomainModelBody;

class BodyType extends Type
{
public function getSQLDeclaration(
array $fieldDeclaration, AbstractPlatform $platform
) {
return $platform->getVarcharTypeDeclarationSQL(
$fieldDeclaration
);
}

/**
* @param string $value
* @return Body
*/
public function convertToPHPValue(
$value, AbstractPlatform $platform
) {
return new Body($value);
}

/**
* @param Body $value
*/
public function convertToDatabaseValue(
$value, AbstractPlatform $platform
) {
return $value->content();
}

public function getName()
{
return 'body';
}
}
namespace InfrastructurePersistenceDoctrineTypes;

use DoctrineDBALTypesType;
use DoctrineDBALPlatformsAbstractPlatform;
use DomainModelPostId;

class PostIdType extends Type
{
public function getSQLDeclaration(
array $fieldDeclaration, AbstractPlatform $platform
) {
return $platform->getGuidTypeDeclarationSQL(
$fieldDeclaration
);
}

/**
* @param string $value
* @return PostId
*/
public function convertToPHPValue(
$value, AbstractPlatform $platform
) {
return new PostId($value);
}

/**
* @param PostId $value
*/
public function convertToDatabaseValue(
$value, AbstractPlatform $platform
) {
return $value->id();
}

public function getName()
{
return 'post_id';
}
}

Don't forget to implement the __toString magic method on the PostId Value Object, as Doctrine requires this:

class PostId 
{
// ...
public function __toString()
{
return $this->id;
}
}

Doctrine offers multiple formats for the mapping, such as YAML, XML, or annotations. XML is our preferred choice, as it provides robust IDE autocompletion:

<?xml version="1.0" encoding="UTF-8"?>
<doctrine-mapping
xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://doctrine-project.org/schemas/orm/doctrine-mapping
http://raw.github.com/doctrine/doctrine2/master/doctrine-mapping.xsd">

<entity name="DomainModelPost" table="posts">
<id name="id" type="post_id" column="id">
<generator strategy="NONE" />
</id>
<field name="body" type="body" length="250" column="body"/>
<field name="createdAt" type="datetime" column="created_at"/>
</entity>

</doctrine-mapping>

 Exercise  
Write down what the mapping would look like in the case of using the Doctrine Embeddables approach. Take a look at Chapter Value Objects or Chapter Entities if you need some help.
..................Content has been hidden....................

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