From the course: PHP: Design Patterns

Unlock the full course today

Join today to access over 22,400 courses taught by industry experts or purchase this course individually.

The decorator pattern in action

The decorator pattern in action - PHP Tutorial

From the course: PHP: Design Patterns

Start my 1-month free trial

The decorator pattern in action

- While most of the frameworks implement this pattern, especially for form generation, those examples are much too complex to demonstrate in the limited time we have here. Instead, let's look at an example that you might see in the real world: content negotiation. When you request data via an API, generally you get back XML, HTML or JSON, based on what you request. In this case, we used different decorator classes. I'll put exactly what we need. We start with our same class that we had before. In the first case, we have a simple HTML renderer that is used to output the name value pairs in the object in question. We can see that here. We simply iterate over the values and output them as we need. In the second class, we have a JSON renderer to simply JSON encode the object and output that. So we take our object that we had before and simply JSON encode that and output that.

Contents