Module design, part 4: Repositories

Module design, part 4: Repositories

August 11, 2013 - by Patrick van Bergen

Tags: ,


In the first part in this series I mentioned that a business object should not not have a save() function to save itself to the database. It should just have simple getters and setters. This way an object is lightweight and very flexible.

Up until recently, we were very fond of the Active Record pattern.  This means that an object is itself responsible for its storage. You can just say


and the object is stored in the database.

We are currently leaving this paradigm, because it ties objects to their storage. In stead, we want to be able to use different storage mechanisms to store the same object. For one thing, we want to be able to "mock" storing objects in a test, so that they are not really stored in the database.

Notice that the object is left with only a single responsibility: managing its fields, as the Single Responsibility principle dictates.

Business objects are now stored and retrieved by object repositories. Each object type may have its own repository, but it may also use a standard repository.

Here's an example repository, again without the function bodies:

class RelationRepository
    public function getRelation($relationId)
    public function saveRelation(Relation $Relation)
    public function removeRelation(Relation $Relation)

    public function getRelations(array $relationIds)
    public function searchRelations(RelationSearchRequest $Request)

This repository is built by the API Factory and passed to the RelationAPI as one of its dependencies.

public static function getRelationAPI(){
    return new RelationAPI(new PrivilegeAPI(), new RelationRepository());

Note that this is an example how the API Factory does not just build APIs as dependencies, but local objects as well.

Having a separate repository does not just mean that the concerns of the object are separated.  It also means that we can swap the storage means of a module. However, in actual practice this is a rare event. For us it is important that we can mock the repository in unit tests and we can test just business logic, not storage.

Photo: Fruit store

Share this post!


Leave a comment!

Italic and bold

*This is italic*, and _so is this_.
**This is bold**, and __so is this__.


This is a link to [Procurios](


A bulleted list can be made with:
- Minus-signs,
+ Add-signs,
* Or an asterisk.

A numbered list can be made with:
1. List item number 1.
2. List item number 2.


The text below creates a quote:
> This is the first line.
> This is the second line.


A text block with code can be created. Prefix a line with four spaces and a code-block will be made.