Mapping Entities Using Annotated Code

When Doctrine was released, a catchy way of showing how to map objects in the code examples was by using annotations.

What's an annotation?
An annotation is a special form of metadata. In PHP, it's put under source code comments. For example, PHPDocumentor makes use of annotations to build API information, and PHPUnit uses some annotations to specify data providers or to provide expectations about exceptions thrown by a piece of code:

class SumTest extends PHPUnit_Framework_TestCase 
{

    /** @dataProvider aMethodName */
    public function testAddition() {
        //... 
    }
}

In order to map the Order Entity to the persistence store, the source code for the Order should be modified to add the Doctrine annotations:

use DoctrineORMMappingEntity;
use DoctrineORMMappingId;
use DoctrineORMMappingGeneratedValue;
use DoctrineORMMappingColumn;

/** @Entity */
class Order
{
/** @Id @GeneratedValue(strategy="AUTO") */
private $id;

/** @Column(type="decimal", precision="10", scale="5") */
private $amount;

/** @Column(type="string") */
private $firstName;

/** @Column(type="string") */
private $lastName;

public function __construct(
Amount $anAmount,
$aFirstName,
$aLastName
) {
$this->amount = $anAmount;
$this->firstName = $aFirstName;
$this->lastName = $aLastName;
}

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

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

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

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

Then, to persist the Entity to the persistent store, it's just as easy to do the following:

$order = new Order(
new Amount(15, Currency::EUR()),
'AFirstName',
'ALastName'
);
$entityManager->persist($order);
$entityManager->flush();

At first glance, this code looks simple, and this can be an easy way to specify mapping information. But it comes at a cost. What's odd about the final code?

First of all, Domain concerns are mixed with Infrastructure concerns. Order is a Domain concept, whereas Table, Column, and so on are infrastructure concerns.

As a result, this Entity is tightly coupled to the mapping information specified by the annotations in the source code. If the Entity were required to be persisted using another Entity manager and with different mapping metadata, this wouldn't be possible.

Annotations tend to lead to side effects and tight coupling, so it would be better to not use them.

So what's the best way to specify mapping information? The best way is the one that allows you to separate the mapping information from the Entity itself. This can be achieved by using XML mapping, YAML mapping, or PHP mapping. In this book, we're going to cover XML mapping.

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

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