This is a bare-bones example of the "loader-mapper" pattern.
There can be multiple layers on top of this for various reasons. For example, you may inject the mapper in a repository which has some caching functionality. This pattern employs the separation of concerns design principle.
The reasoning behind building an entity
like this would be
- Easy unit testing (because of DI)
- Code reusability
- Ability to easily switch datasource technologies
- Easier refactoring
- Less / Easier to manage merge conflicts
The loader has the single responsibility of loading requested data from a datasource. The data is, usually, returned as a flat array for mapping to a "dumb" object (POPO)
The Mapper
has the single responsibility of mapping data from the Loader
into an Entity
object.
This is accomplished via the private map()
function.
I prefer to have this function return an
EntityCollection
rather than an array so you will always know what you are dealing with.
Generic placeholder for whatever object you are trying to create. (User, Session, Book, etc.)
php example.php
- phive to install build tools
- phpab(
phive install phpab
) to generate autoloader - ant to use build.xml targets
./build/install-tools.sh
ant