Handling relationships with the Data Mapper pattern Handling relationships with the Data Mapper pattern php php

Handling relationships with the Data Mapper pattern


If you look at Martin Fowler's text that describes how the DataMapper works, you'll see that you can use one query to get all the data that you need and then pass that data to each mapper, allowing the mapper to pick out only the data that it needs.

For you, this would be a query that joins from Team to Player, returning a resultset with duplicated Team data for each unique Player.

You then have to cater for the duplication in your mapping code by only creating new objects when the data changes.

I've done something similar where the equivalent would be the Team mapper iterating over the result set and, for each unique team pass the result set to the Player mapper so that it can create a player and then add the player to the team's collection.

While this will work, there are problems with this approach further downstream...


I have a possible solution to this problem that I have implemented successfully in one of my projects. It is not so complex and would use only 2 queries in the example described above.

The solution is to add another layer of code responsible for handling relationships.

For instance, we can put that in a service class (which can be used for other stuff as well, not only handling relationships).So let's say that we have a class TeamService on top of Team and TeamMapper. TeamService would have a method getTeamsWithRelationships() which would return an array of Team objects. getTeamsWithRelationships() would use TeamMapper to get the list of teams. Then, with the PlayerMapper, it would get in only one query the list of players for these teams and set the players to the teams by using a setPlayers() method from the Team class.

This solution is quite simple and easy to implement, and it works well for all types of database relationships. I guess that some people may have something against it. If so, I would be interested to know what are the issues?