Hello World!

by andrew

Next chapter is quite complex. Literally complex. And I treat it as a last chapter of the book since it is a last chapter when you learn a new design pattern in a detailed way. And the last one of them is quite popular in many PHP frameworks. It is called MVC (Model-View-Controller). Maybe this is why it took me so long to write about it

Frankly, I’ve been quite busy for last months and we released our new feature in Wikia: Wikia Maps. Additionally, I contributed to few other side projects, visited Velocity EU conference in Barcelona and just couldn’t find time to write about almost last chapter in the book I’ve been describing here.

Compound patterns

Enough of excuses! Let me continue describing the chapter. It is quite long one and I will split it into two posts. However, it does not mean the posts are going to be short. Let’s start with the first one.

There is quite artificial example at the beginning demonstrating how design patterns can work together. And this post will describe it. It is somehow back to the past — together with authors we are implementing a duck simulator! Almost the same one from beginning of the book.

First we implement a Quackable interface which is implemented by all other classes such as: MallardDuck, RedheadDuck, DuckCall and RubberDuck. Finally we implement the simulator itself and…

$ php app.php
Duck Simulator
Quack
Quack
Kwak
Squeak

…done.

And here comes the first change: there are also geese around the place where ducks are. The simplest way is to implement a Goose class and make it quack. But geese can not quack! They can with a help of an adapter. We modify a little bit our simulator so it creates a GooseAdapter class instance. The adapter just overwrites the quack() method of Quackable interface which makes the simulator still work properly.

Another change is a request from a quackologist to count all the quacks done by ducks. We create a decorator which gives ducks a new behavior — counting behavior. New QuackCounter class wraps Quackable objects and delegate the quack() call to the instance it is decorating but also increases the counter.

It provides a new static method to return the count. It is pretty straightforward and clean because we do not modify the Quackable class itself. The last step with this change is to wrap each Quackable object which we instantiate in a QuackCounter decorator and call QuackCounter::getQuacks() method at the end of our simulator.

What the Quackologist notice is the inconvenience of decorating each instance. He is right and this is another change in our program we want to make. To hermitize the process of wrapping each Quackable object in a decorator we use a factory. The process is quite easy and we do not need to focus more on it (you can check it later in attached files).

The next requirement is to give our Quackologist possibility to manage a flock of ducks. Here comes the composite and itterator patterns for help. We create Flock class which implements our Quackable interface. It has add() method and quack() method.

The first one adds a Quackable objects into an array. The last one iterates through the objects and calls quack() method on them. In the simulator we just create flock of ducks and flock of mallards only and execute quack() on them.

The Quackable interface extends QuackObservable, new Quackologist class implements Observer. After adding few more methods to our classes which implements Quackable interface and two lines to the simulator — it is done.

The example was also a preludium to second part of the chapter: The King of Computed Patterns. This is the name given by authors to Model-View-Controller design pattern which we will get to in my next blog post.

Hi! I’ve been very busy since the beginning of the year. Hopefully I’ll write here something longer soon but today I only found few minutes to update the Design patterns: adapter post after reading an interesting article on Sitepoint.

New 2014 year did not start easy for me in terms of describing new design pattern I have learnt by reading the book. The cause of it is next chapter I have read more than a month ago. It describes new proxy pattern but it describes it mostly in Java environment. However, it does not mean we use the pattern only in Java applications.

Book example

The history of cooperation with Mighty Gumball, Inc. continues. The CEO asks us for a better monitoring for the gumball machines. At first we add location property to GumballMachine class, assign a value to it via the constructor and added two getters: location getter and state getter. After these changes in existing class we create GumballMonitor class which is rather simple:

But once we show it to the CEO we learn the output is alright but he was not clear enough with us. He wants a remotely check the status of different machines (we are supposed to be Internet generation!). That changes a lot. However, not as much as we might think at the beginning. One of developers comes up with an idea of proxy and using Java RMI mechanism (java.rmi.* package). On next pages of the chapter you can read about it more. Basically, I do not think you need similar architecture in the world of web development and PHP When I read it I thought that instead of RMI Stubs and RMI Skeletons we can just use HTTP protocols. Therefore, I will not describe the Java implementation here — it is in the book if you are interested Let’s jump to the proxy pattern definition:

The Proxy Pattern provides surrogate or placeholder for another object to control access to it.

Proxy pattern’s diagram.

Later on we learn different kinds of proxy patterns:

remote proxy — manages interaction between a client and a remote object,

virtual proxy — controls access to an object that is expensive to instantiate,

firewall proxy — controls access to a set of network resources, protecting the subject from “bad” clients,

smart reference proxy — provides additional actions whenever a subject is referenced, such as counting the number of references to an object,

caching proxy — temporary storage for results of expensive operations; it can also allow multiple clients to share the results to reduce computation or network latency,

synchronization proxy — provides a safe access to a subject from multiple threads,

complexity hiding proxy — hides the complexity of and controls the access to a complex set of classes (this is sometimes called the Facade Proxy for obvious reasons); the complexity hiding proxy differs from facade pattern in that the proxy controls access, while the facade pattern just provides an alternative interface,

copy-on-write proxy — controls the copying of an object by deferring the copying of an object until it is required by a client; this is variant of virtual proxy.

It’s about the time to put another design pattern post on my blog. This time I’ll write about state design pattern about which I read in the book. State pattern helps objects to control their behavior by changing their internal state. I also learnt it’s really similar to the first pattern in the book which was also mentioned by me on this blog: strategy pattern.

Book example

Imagine you’re working in B2B software company and Mighty Gumball, Inc. is asking you for help. They present you this diagram:

Mighty Gumball, Inc. gumball machine flow

and ask you to implement it in PHP. You can put everything in one class and implement it in this way:

I shorten the example above because the rest of the methods were similar. The job we’ve done was really fast and software we created met all the requirements. It was tested and it just works. Our client is happy with the results. The job is done. Is it?

Mighty Gumball, Inc. did their own tests and they didn’t find any bugs. They are happy with our software and because it’s gone so smoothly they’d bring their machines to the next level and ask us about a small change. They want the machine to give a free gumball from time to time. Every 1 of 10 turns of the crank should give 2 gumballs. How would we implement it with our code? Well, we’d add new WINNER constant which will be new state of the machine and then… yes, then we’d have to modify all methods so they react correctly on the new WINNER state. It clearly tells us the previous design wasn’t good enough. We need to re-write the application at this point.

We should encapsulate what varies here which is the state of gumball machine. We’ll put each state’s behavior in its own class and then every state will just implement its own actions. The gumball machine will just delegate to the state object that represents the current state. This way we’ll favor composition over inheritance.

Implementation of other state classes is quite straight-forward. You can download all examples and you’ll notice that after implementing SoldOutState, NoQuarterState, HasQuarterState and SoldState classes, adding new methods and some changes in GumballMachine class we don’t have to touch the app.php file. It means that we made all the changes in code without changing API of GumballMachine class.

Implementing new feature such as 10% chance of getting two gumballs wasn’t hard as well. I created new WinnerState class which was really similar to SoldState and with few lines added to HasQuarterState the work was completed! A lot easier than adding another else-ifs.

Of course I could’ve implemented the new feature in already existing SoldState class but once again it was a trade-off I made. I decided to duplicate a little bit of code to keep SoldState class being responsible for only one thing. If I would’ve done it the other way imagine what could happen if the promotion ends? Or the stakes of the contest change?

OK, at the end let me introduce you the official definition of the state design pattern:

The State Pattern allows an object to alter its behavior when its internal state changes. The object will appear to change its class.

State pattern’s diagram.

At the diagram the context is the class that can have a number of internal states (in example GumballMachine). The state interface defines a common interface for all concrete states; the states all implement the same interface, so they’re interchangeable. Whenever the request() is made on the context it is delegated to the state to handle. Each concrete state provides its own implementation for a request. In this way, when the context changes state, its behavior will change as well.

The diagram of state pattern is essentially the same as strategy pattern’s diagram. However, the patterns differ in their intent. I read in the book:

(…) With the state pattern, we have a set of behaviors encapsulated in state objects; at any time the context is delegating to one of those states. Over time, the current state changes across the set of state objects to reflect the internal state of the context, so the context’s behavior changes over time as well. The client usually knows very little, if anything, about the state objects.

With strategy, the client usually specifies the strategy object that the context is composed with. Now, while the pattern provides the flexibility to change the strategy object at runtime, often there is a strategy object that is most appropriate for a context object.

(…) In general, think of the strategy pattern as a flexible alternative to subclassing; if you use inheritance to define the behavior of a class, then you’re stuck with that behavior even if you need to change it. With strategy you can change the behavior by composing with a different object.

Think of the state pattern as an alternative to putting lots of conditionals in your context; by encapsulating the behaviors within state objects, you can simply change the state object in context to change its behavior.

If it doesn’t explain the difference good enough on the next pages in the book you can read a dialogue between strategy pattern and state pattern which explains it once again and helps you remember it

Other examples

Except artificial book-oriented examples on the Internet I found one nice idea/example. Actually it’s a group of posts called PHP Game Making by Bill Sanders. In the second part from the group he demonstrates usage of state pattern in, known from The Big Bang Theory, R-P-S-L-S game. Other than that there are PHP implementations for different machines with buttons Searching the web I also found two interesting pages which are generally about design patterns in PHP. Maybe you’ll find them interesting:

While describing iterator pattern on previous post I mentioned it was a part of a bigger chapter in the Head First: Design Patterns book. The second design pattern described in the chapter is called composite. The composite pattern helps us create tree structures in our code. The book example this time is pretty straight-forward but the end of it shows the power of iterator and composite together.

Book example

We’re still with our merged restaurants. It’s easy to add more restaurants and merge their menus into one. We have our iterators to traverse through all menus and print them. But just when we thought it was safe we received a request we hadn’t expected: they want us to implement sub-menu.

The time has come to refactor all the code we’ve created so far! We’ve reached a level of complexity such that if we don’t rework the design now, we’re never going to have a design that can accommodate further acquisitions or sub-menus. Is the composite pattern the direction we should follow?

The Component defines an interface for all objects in the composition: both the composite and the leaf nodes. It may implement a default behavior for add(), remove(), getChild() and its operations. We’re going to implement MenuComponent in this place.
The Composite‘s role is to define behavior of the components having children and to store child components. In our implementation Menu class will become composite.
The Leaf defines the behavior for the elements in the composition. A leaf has no children. MenuItem class will be our leaf class.
Note that composites (Menu) and leaves (MenuItem) implement operations which may not make sense (for example implementing add() method in MenuItem class) so in that case an exception might be generated. That’s why we start with the MenuComponent class which is rather simple:

The constructor and getters don’t change at all so I removed them from the listing above. The only changes are:
the class inherits now from MenuComponent and I added getListing() method which returns a string with all information connected to the menu item. All other methods inherited from MenuComponents will throw an exception if used on MenuItem instance.

It has less properties (and getters) but one of the properties is very important: $menuComponents. Within it Menu stores all its children. This class overwrites methods connected to children operations: add(), getChild(). We don’t want now the functionality of removing, so we just not overwrite the method here (it’ll throw an exception from MenuComponent class).

And this is the place (getListing() method of Menu class) where we use learnt earlier iterators. Thanks to the fact that we iterate through aggregates with Menu and MenuItem instances and they both implement print() method we’re sure the code is solid and does what we want — it prints all elements: menus and menus’ items.

We don’t need the method which we pass menus’ iterator to. All we need is to recursively get all menus listed by calling getListing() on the top element and then print its results on the screen.

And this is the end of our refactoring. The chapter in the book continues with explaining why the design principle learnt in the same chapter wasn’t followed this time. Surely, the composite pattern manages hierarchy and it performs specific operations related to leaves. Of course this is a phenomenon which happens quite often in software development — classic case of tradeoff. We can say Signle Responsibility design principle is being trade for transparency. Transparency which makes the client treat leaves and composites uniformly. An example composite application can be as always downloaded here.

Other examples

Nice example of composite pattern is described by Craig Sefton on his blog. Craig describes how to use the pattern to be able to create not only one-level-flat lists from our real life.
Basically, that was my thought that composite is a great way to handle complex lists. And what are lists used for on the Internet? Menus! Probably there are lots of menu implementations using composite pattern. Maybe I’ll check it later

However, not only such simple components as menus can be handled by composites. Few years ago I learnt that Symfony 1.4 used decorator pattern for their views system. While looking for examples of composite pattern usages I’ve found very nice articles by Alejandro Gervasio. He describes there the mentioned way but also the other way: using composite design pattern to create view system!
Mentioning Symfony and more complex systems build with composite pattern, Hugo Hamon, presented practical usage of design patterns during this year PHP Benelux. You can see on his presentation composite used to build form builder.

I think these examples proves how useful the composite design pattern is. Sometimes, we have to make this tradeoff in favor of transparency.

Next chapter in the book is the longest one. But I will split it into two posts because it’s about two design patterns. The first one’s name is: iterator and it was mentioned at least once before. I recall it while describing examples of adapter pattern usage. The iterator pattern, unlike other design patterns, helps us encapsulate an iteration. Let’s start with the book example.

Book example

Many previous examples were connected to cooking and this time it’s similar. We have two places which are going to be merged. Objectville Dinner and Objectville Pancake House agreed to have the same implementation of MenuItem:

But they have two different implementations of their menus and no one is willing to change it. The Java examples from the book may reflect the issue better but I’ll try to describe it with PHP code, anyway. Originally, PancakeHouseMenu uses ArrayList structure whereas DinnerMenu just a regular Array. There is only array type in PHP and my examples look a little bit different than the Java onces:

I implemented simple ArrayList class in the PHP examples to make it easier to present the issue. And it exists in a client code which has to use the two menus — waitress One of the waitress’ functions would be printing the menus. To achieve this it’ll have to create instances of PancakeHouseMenu and DinnerMenu and call on them getMenuItems() methods:

Imagine there are more restaurants merged and for each of them we’ve got different menu and to display it we need to add more loops… How to avoid it? Well, as always let’s see what’s changing element here. It’s the iteration through different items. And we can encapsulate it with iterator design pattern which diagram and definition are presented below.

Iterator design pattern

The Iterator Pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

What we need to do is:

Create iterators for our menus.

Rework the menu with iterator.

Fix up the waitress code.

Iterators for both menus are similar. The difference is in the implementation of next() and current() methods:

Changes in menu classes are simple: we add a getter which returns menu’s iterator and we remove getMenuItems() methods because we don’t need it anymore and what’s more important: we don’t want to expose internal implementation of a menu.

Our waitress function of printing menu is handled now by two methods: first one creates menu iterators’ instances and passes them to the second method which in one loops prints items for both menus.

But the work done doesn’t reflect in 100% iterator pattern diagram. That’s because the client code depends on two classes where it could refer to each menu object using an interface rather than concrete class. Let’s create a Menu interface with createIterator() method. DinnerMenuIterator and PancakeHouseMenuIterator implement the new interface and reduce the dependency between Waitress and the concrete class.

Later we’re informed about another place being merged with our Pancake House and Dinner. The above change makes it easy to take it into account. The new place’s menu just have to implement Menu interface, make createIterator() method available and we can use it in our Waitress class. However, a small change there will make code easier to read and maintain. Let’s pass the menus’ objects to the Waitress class as an array. Then in printMenu() method just iterate through them and pass each’s iterator to doPrintMenu() method:

Now, all the work is done and seems solid. We lost names of the menus but we could add the names to each menu. We also followed another design principle: single responsibility principle. It says that a class should have only one reason to change. If we would have left the classes responsibility of handling their aggregates and one more responsibility of iterating through aggregated elements then there would be two reasons to change. They would change if collections change and if the way we iterate through the collections changes. We know we want to avoid change in a class like the plague — modifying code provides all sorts of opportunities for problems to creep in. The above snippets are taken from full PHP example of iterator pattern usage I’ve written — feel free to take a look at it.

Other examples

Difference between types in Java and PHP was the hardest part to write this post’s code examples. Reading the part of the chapter about iterator design pattern was easy and with Java’s Array, ArrayList or Hashtable types it was even easier to understand how iterators help. Those built-in objects have their method’s such as iterator() which returns an iterator instances.

However, once you start looking for examples of usage in Google you’ll find a lot of nice examples. You’ll find also quite markable words of one of the well known people from PHP world, founder of Sensio Labs:

(…)PHP also have a lot of awesome features; at least two of them are in my opinion largely underused: Iterators and Streams.Fabien Potencier

Chapter eight of the book is about template method pattern. It’s another way of encapsulation. The examples shows how to encapsulate piece of algorithms so the sub-classes can hook themselves right into computation any time they want. We learn a new design principle too!

Book example

First example is a real one from real life! We implement code which makes a coffee or tea At the beginning we’re presented with code:

Probably many of the readers are worried about the code duplication. And indeed, when we have code duplication it’s a signal we need to clean-up the design. We’re asked to draft possible class hierarchy. At first it’s probably made of three classes. The base class has prepareRecipe(), boilWater() and pourInCup() methods because they’re clearly common parts of code for Coffee and Tea classes and they don’t differ anyhow of each other. Two other classes are the ones presented above: Coffee and Tea. However with the new hierarchy contain less code and extend the brand new base class. They overwrite prepareRecipe() method and have two new methods each class (brewCoffeeGrinds(), addSugarAndMilk(), steepTeaBag() and addLemon()).

That was a move in the right direction but we can do better! Next step in the book is taking a look at the bigger picture. We abstracted boilWater() and pourInCup() methods but the ones left in sub-classes are practically the same! They just apply to different beverages. So, basically we can abstract prepareRecipe().
Brewing coffee grinds and steeping tea bag are, in general, brewing a beverage. And adding sugar, milk and lemon is nothing else than adding condiments the the beverage. At the end our parent class prepareRecipe() looks like this:

Then in the same class we define abstract methods brew() and addCondiments(), so the sub-classes have to implement them. We remove overwritten prepareRecipe() methods from Coffee and Tea classes and implement there only those two new methods. Here you can find final and working code.

As you suspect the prepareRecipe() method in our super class is nothing else than an example of template method design pattern usage. The book’s diagram and definition are as follows:

A template method pattern’s diagram

The Template Method Pattern defines the skeleton of an algorithm in a method, deferring some steps to sub-classes. Template Method let’s sub-classes redefine certain steps of an algorithm without changing the algorithm’s structure.

After learning the definition and diagram we read about pretty common practice of using hooks methods together with the template method pattern. Hooks are methods injected into our template method to make it more flexible/extensible. Going back to our coffee&tea example a hook could be added to prepareRecipe() method and depending on its result the addCondiments() method would be executed. New parent class code written in this way looks like:

The sub-classes can overwrite the hook method and modify it but there isn’t “a must” to do so. In the code examples package, I put link to earlier, you’ll find working example of using hooks. I must admit that hooks in object-oriented way are even more useful in my eyes than hooks I’ve seen in some PHP code-bases.

After introduction to hooks we’re presented with another design principle: The Hollywood Principle. This time it’s pretty easy to remember: “Don’t call us, we’ll call you”. It helps us with preventing “dependency rot” in our code-base. Dependency rot happens when high-level class is depending on low-level classes which are depending on sideways components which are depending on low-level classes, and so on. When rot sets in, no one can easily tell the way a system is designed.
With the new principle we allow low-level components to hook themselves into a system, but high-level components determine when they are needed, and how. How does it work in our template method example? CaffeineBeverage has control over algorithm for the recipe, and calls on the sub-classes when they’re needed for an implementation of a method. This class is our high-level component which tells Coffee and Tea classes “don’t call us, we’ll call you”. The sub-classes never calls the abstract class directly. Clients of beverages will depend only on CaffeineBeverage abstraction rather than a concrete sub-classes. And this is how we reduce dependencies in the overall system.

After the new design principle authors show more examples of template method pattern implementations in Java. Not all of them depends on inheritance. There is an example with Comparable interface and compareTo()template method. The Java Arrays class is responsible for different arrays’ manipulation such as sorting. Arrays class implements all required steps of sorting but it let’s other classes decide on how elements are compared to each other.
The other two Java examples are examples of different classes and their hooks. JFrame class and its paint() hook method and Applet class with several hooks:

init() allows the applet to do whatever it wants to initialize the applet the first time,

start() allows the applet to do something when the applet is just about to be displayed on the web page,

stop() if the user goes to another page the stop() hook is used and the applet can do whatever it needs to do to stop its actions,

destroy(),

paint().

Other examples

Putting “php template method” in Google results in links to web pages which occurs the most often when you’re looking for examples of design patterns in PHP. Two of them describes the same abstract example of displaying books titles and authors. There is also well-known blog of author I’ve mentioned before: she had similar idea to mine — write about design patterns learn from Head First. Design patterns. It was a nice to see Sitepoint name within the results links (I really enjoy reading their articles). Example there describes how to use template method for rendering different jQuery sliders. It’s nice and more practical example than the ones described shortly before. One more nice example with step after step explanation is about implementing classes representing tweet text.

Separate paragraph needs to be written about hooks mentioned in the chapter. In all examples: books and the one I found on the Internet you read about them as method in the abstract class which can be overwritten by sub-classes. It’s clearly object-oriented and PHP wasn’t an object-oriented language. Therefore, you can find many PHP applications with the idea of hooks. In Wikia we use MediaWiki code and there is quite a long list of hooks you can hook into. WordPress since version 2.1 split hooks into two groups: filter and action hooks. Another blog application, Drupal, had its own hooks list but since version 8 they started using many Symfony’s components as well as its event listeners which allows to hook into Symfony application. Symfony, Zend, CodeIgniter and many other PHP frameworks uses different approaches to allow a developer to hook into their core code. But these hooks are a little bit different than hooks explained during learning template method design pattern. So let me stop at this point.

The adapter pattern mentioned in previous post was only one of two design patterns mentioned in seventh chapter in the book. When you continue the reading you’ll find interesting discussion between a decorator and an adapter. It leads to the conclusion that both of these two design patterns seem to look similar on a paper but they are different in their intent. The end of this discussion as well as introduction to facade pattern is a simple table:

Pattern

Intent

Decorator

Converts one interface to another

Adapter

Doesn’t alter the interface but adds responsibility

Facade

Makes an interface simple

Book example

Before we learn the definition and schema of facade pattern we read about another real life example. It’s connected to the obsession some of us or our friends had: building a home theater. Usually it made of many of different components:

Many components of a home theater system

If you want to watch a movie there is few-steps procedure to set all the components of your home theater. Once you’ve done it you’re already tired. If you manage and finish the movie you have to repeat all the steps in reverse. Listening to a CD or a radio isn’t easier either. And things are getting more complex when you want to add new components. Facade pattern is the right design pattern to help you!

A home theater system with facade pattern used

The Facade Pattern provides a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.

An example application can be downloaded as usual. Feel free to play with it However, it’s not the end of the chapter. The facade design pattern not only makes an interface simplier for a client but also helps us obligate to another OO principle. The principle of Least Knowledge as known as Law of Demeter: talk only to your immediate friends. It means when you’re designing an application, for any object, be careful of the number of classes it interacts with and also how it comes to interact with those classes. It prevents us from creating systems with a large number of classes coupled together so that changes in one part of the system cascade to other its parts. When you don’t apply this principle you’re probably creating fragile applications that will be costly to maintain and complex for others to understand. To make it easier you can take any object and then from any method in that object, the principle tells us that we should only invoke method that belong to:

the object itself,

objects pass in as a parameter to the method,

any object that methods creates or instantiates,

any components of the object (objects that are referenced by an instance variables).

The facade pattern is really helpful for us if we want to apply The Principle of Least Knowledge in our bigger systems. We can tell it just by looking at its diagram:

An example of how usage of facade pattern helps obey the principle of least knowledge

The client is coupled only with the facade which makes the client simple and flexible. Changes in any of subsystem’s classes don’t affect the client.

There weren’t any code snippets presented in the post content but as always you can download some code examples and take a look at them.

This time I’m writing about adapter pattern. This is an easy one to understand. Why? Because our world is full of real-life adapters. The authors of the book gives just this simple example about AC power adapter. We use it while traveling from Europe to United States because we want our laptops work there. So, we take our laptop’s plug-in connect it with an adapter and then plug it into US type wall outlet.

Book example

Code example in the book is quite unreal. Let’s go back to ducks’ example! It’s a little bit far-fetched example but perfectly shows what adapter pattern does for us. We’ve got simplified version of Duck interfaces and classes:

Because of some strange reasons we can’t use Duck sub-classes anymore but we are allowed to use Turkey sub-classes instead. But instances of one and another class have different interfaces and to make it easy and possible to do we’re going to write an adapter class:

After this a little bit unrealistic example authors of the book goes back to the AC power adapter example and explain us how a client use adapter pattern:

The client makes a request to the adapter by calling a method on on it using the target interface.

The adapter translates the request into one or more calls on the adaptee using the adaptee interface.

The client receives the results of the call and never knows there is an adapter doing the translation.

Finally, we get to adapter pattern‘s definition:

The Adapter Pattern converts the interface of a class into another interface the client expects. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.

Adapter pattern diagram from Head First: Design Patterns

The adapter’s introduction part in the chapter ends with short explanation about second type of adapters: class adapters. The solutions presented above were object adapter solutions. In programming languages where multiple inheritance is available you can create class adapter instead of object adapter. The only difference is that we use multiple inheritance instead of composition to translate one interface to another.

Then we have a really nice real java-life example There were enumerators in some old Java version and they were replaced with iterators. The Enumeration interface looked like:

So, the answer for any legacy code that exposes an interface you’d like to replace with a better version is adapter pattern

The code example above as always can be downloaded from here. Notice that my PHP version of Iterator class was named JavaIterator that’s because I didn’t want to conflict with PHP built-in iterator interface.

Other examples

The examples in the book was quite unreal or strictly connected to Java world. But Google is your friend and there are lots of nice PHP examples. I found two twitter services examples on the first page of Google results presented to me. The first post has very nice introduction to adapter pattern. The second is just a nice example with using an adapter to translate more than one interface into target one. I also found that the lady with similar idea of mine wrote more about design patterns and you can find there the post about adapter pattern. She just stopped tagging them with “Head First Design Patterns” tag

Update (2014-04-09)
Today I read an article about interesting library called Flysystem. Once you visit the repository page on Github you’ll notice it’s nothing else as a group of adapters to different file systems. Pretty simple but very useful library. I encourage you to give it some time, read the article and play with the Flysystem itself