Serialized LOB and Ad Hoc ORM

If the addition of searching capabilities to the Value Objects attributes is not important, there's another pattern that can be considered: the Serialized LOB. This pattern works by serializing the whole Value Object into a string format that can easily be persisted and fetched. The most significant difference between this solution and the embedded alternative is that in the latter option, the persistence footprint requirements are reduced to a single column:

CREATE TABLE ` products` (
id INT NOT NULL,
name VARCHAR( 255) NOT NULL,
price TEXT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

In order to persist the Product Entities using this approach, a change in the DbalProductRepository is required. The Money Value Object must be serialized into a string before persisting the final Entity:

class DbalProductRepository extends DbalRepository implements ProductRepository
{
public function add(Product $aProduct)
{
$
sql = 'INSERT INTO products VALUES (?, ?, ?)';
$stmt = this->connection()->prepare(sql); 
$stmt->bindValue(1, aProduct−>id()); 
$stmt->bindValue(2, aProduct−>name()); 
$stmt->bindValue(3, $this−>serialize($aProduct->price()));

// ...
}

private function serialize($object)
{
return serialize($object);
}
}

Let's see how our Product is now represented in the database. The table column price is a TEXT type column that contains a serialization of a Money object representing 9.99 USD:

mysql > select * from products G
*************************** 1.row***************************
id : 1
name : Domain-Driven Design in PHP
price : O:22:"DddDomainModelMoney":2:{s:30:"DddDomainModel\
Money amount";i :
999;s:32:"DddDomainModelMoney currency";O : 25:"DddDomainModel\
Currency":1:{
s:34:" DddDomainModelCurrency isoCode";s:3:"USD";}}1 row in set( 0.00 sec)

This approach does the job. However, it's not recommended due to problems occurring when refactoring classes in your code. Could you imagine the problems if we decided to rename our Money class? Could you imagine the changes that would be required in our database representation when moving the Money class from one namespace to another? Another tradeoff, as explained before, is the lack of querying capabilities. It doesn't matter whether you use Doctrine or not; writing a query to get the products cheaper than, say, 200 USD is almost impossible while using a serialization strategy.

The querying issue can only be solved by using Embedded Values. However, the serialization refactoring problems can be fixed using a specialized library for handling serialization processes.

..................Content has been hidden....................

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