Extra Behavior

interface PostRepository 
{
// ...
public function size();
}

The implementation could look like this:

class DoctrinePostRepository implements PostRepository
{
// ...

public function size()
{
return $this->em->createQueryBuilder()
->select('count(p.id)')
->from('DomainModelPost', 'p')
->getQuery()
->getSingleScalarResult();
}
}

Adding additional behavior to a Repository can be very beneficial. An example of this is the ability to count all the items in a given collection. You might think to add a method with the name count; however, as we're trying to mimic a collection, a better name would instead be size:

You're also able to place specific calculations, counters, read-optimized queries, or complex commands (INSERT, UPDATE, or DELETE) into the Repository. However, all behavior should still follow the Repositories' collection characteristics. You're encouraged to move as much logic into Domain-specific stateless Domain Services as possible, instead of simply adding these responsibilities to the Repository.

In some instances, you won't require the entire Aggregate for simply accessing small amounts of information. To solve this, you can add Repository methods to access these as shortcuts. You should make sure to only access data that could be retrieved by navigating through the Aggregate Root. As such, you shouldn't allow access to the private and internal areas of the Aggregate Root, as this would violate the laid out contractual agreement.

For some use cases, you'll require very specific queries that are compositions of multiple Aggregate types, each returning specific information. These queries can be run and then returned as a single Value Object. It's very common for Repositories to return Value Objects.

If you find yourself creating many use case optimal finder methods, you may be introducing a common code smell. This could be an indication of a misjudged Aggregate boundary. If, however, you're confident that the boundaries are correct, it could be time to explore CQRS.

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

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