The Composite Design Pattern Explained (with PHP)

The Composite Design Pattern Explained (with PHP) Thumbnail image

You use the composite design pattern when you have items, and also groups of items, and you want to use them in the same way.

For example (and this is a very simplified example!), you have a MenuItem (a single item on a navigation menu), and a MenuItemGroup (a collection of child MenuItem objects. You would make an interface (MenuInterface, with methods such as AllLinks) and both MenuItem and MenuItemGroup would implement this interface.

In the example above, you could have an object (that you know implements MenuInterface, which has a render()) and you can do something simple such as this:

  1. $items [
  3. new MenuItem("home"),
  4. new MenuItemGroup(['about us','services','contact us']),
  5. new MenuItem("login"),
  7. ];
  8. foreach($items as $item) {
  9.   echo "<li>" . $item->render() . "</li>\n";
  10. }

For single menu items, obviously it would output a single, normal link. But render() on the Menu Item Group would have some logic in it to wrap it's child Menu Items (or maybe it even contains more Menu Item Groups!) in some form of a dropdown menu.

The advantages of using the composite design pattern is that your code (such as the foreach loop above) doesn't have to check what type an object is, as it knows it implements the interface and you can call the same methods on single items or groups of items and it will work as expected.

Design pattern type: Structural design pattern

Subscribe to my spam free newsletter for other Laravel and Vue updates like this

I never spam, and only email when I have a good in-depth post published on my site (mostly about Laravel and Vue). You can also follow me on social media to get updates.

webdevetc profile pic

I've been working as a software developer for many years (with the last few years specialising in Laravel and Vue). I mostly write about PHP and JavaScript/TypeScript on this site. Contact me here. Need to hire a contract software developer in London, UK (or freelance)? Contact me and check my availability.

Leave a Comment