O'Reilly logo

PHP Hacks by Jack D. Herrington

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Hack #72. Link Up Two Modules with an Adapter

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 RecordGraphAdapter sitting between the TextGraph on the left and the RecordList on the right. The TextGraph object very nicely specifies the format it expects for data using an abstract class called TextGraphDataSource. The RecordList is a container class that has a list of Records, where each Record contains a name, age, and salary.

The adapter sitting between the graph and the data

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 for the TextGraph by turning the data into a TextGraphDataSource object.

The Code

Save the code in Example 7-6 as adapter.php.

Example 7-6. An adapter example using a text ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required