Use an adapter class to transfer data between two modules when you don't want to change the API of either module.
Sometimes you have to get data from two objects, each of which uses a different data format. Changing one or both objects just isn't an option because you'll have to make all sorts of other changes in the rest of your code. One solution to this problem is to use an adapter class. An adapter is a class that understands both sides of the data-transfer fence and adapts one object to talk to another.
The adapter demonstrated in this hack adapts data from a mock database object into data usable by a text-graphing engine.
Figure 7-6 shows the
sitting between the
TextGraph on the
left and the
RecordList on the right.
TextGraph object very nicely
specifies the format it expects for data using an abstract class called
RecordList is a container class that has a
Records, where each
Record contains a name, age, and
Figure 7-6. The adapter sitting between the graph and the data
For this example, I want a graph of the salaries. The adapter's
job is to take data from the
RecordList and convert it into a form suitable
TextGraph by turning the data
Save the code in Example 7-6 as adapter.php.
Example 7-6. An adapter example using a text ...