O'Reilly logo

Learning PHP Design Patterns by William Sanders

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

Chapter 7. The Adapter Pattern

It is not the strongest of the species that survives, nor the most intelligent that survives. It is the one that is the most adaptable to change.

Charles Darwin

The measure of intelligence is the ability to change.

Albert Einstein

Science always has its origin in the adaptation of thought to some definite field of experience.

Ernst Mach

What Is the Adapter Pattern?

This chapter is a two-for-one package: object and class Adapters. This chapter has many lessons, but one of the most interesting is seeing the difference between using inheritance and using composition. The class scope version of the Adapter design pattern uses inheritance, as can be seen in the class diagram in Figure 7-1.

Adapter class diagram using inheritance
Figure 7-1. Adapter class diagram using inheritance

In the class diagram, one implementation of the pattern is to have one class with dual inheritance. As you will see, dual inheritance is not allowed in PHP 5, but there are alternatives to dual inheritance where the pattern can be correctly implemented with a combination of inheritance and implementation.

As you know, an important dictum of design patterns is to favor composition over inheritance. In looking at the second Adapter pattern, the Adapter participant uses composition to hold a reference to the Adaptee instead of inheritance.

Figure 7-2. Adapter class diagram using composition

Generally, composition is favored over inheritance ...

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