Understanding Decorator Pattern with PHP implementation

Mouthwatering burger in the mid of the night from: http://bit.ly/38QrlvT

The design patterns are cool! I tried to learn a few design patterns. But failed always. It’s hard to memorize and I forget easily 🙄. At least I find it hard. But, recently I came to know a design pattern which is the Decorator Design Pattern. Before I dive into the code let’s just have an understanding of what it is.

Suppose, you went to have burgers with your friends. The burger costs you $4. But you want to add some addons. Extra cheese & sauce. You may also like an extra patty. But they also require some extra cash to be paid. This is in terms of the design pattern called the Decorator Pattern. It’s still a burger but it requires some extra price to decorate. Let’s dive into the code to get an idea.


  • So in the above example, we defined an interface FoodItem where we defined an abstract method cost which needs to be implemented by the concrete classes.
  • Next, we defined a basic burger where we implemented the FoodItem interface. The cost for the burger is $4;
  • Next, as we want to decorate our burger with some cheese, we defined a new class which also implements FoodItem but also takes a FoodItem in the constructor (Burger in our case). So, the cost will be the actual burger’s cost + cheese’s cost.
  • Next, we need to add another patty to our burger. So we implemented the FoodItem in the Patty class and the cost should be the burger’s cost + patty’s cost.
  • Finally, if we want a burger with cheese & an extra patty then the price will the cost of the Burger + the cost of the Cheese + the cost of the Patty.

So what finally?

To implement a decorator pattern, you’ll need to satisfy an interface and with that, you’ll need to accept a class that also satisfies the same interface. In short, this is a decorator pattern.

Happy coding. ❤

procrastinator | programmer | !polyglot | What else 🙄

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store