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 [
  2.  
  3. new MenuItem("home"),
  4. new MenuItemGroup(['about us','services','contact us']),
  5. new MenuItem("login"),
  6.  
  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 updates like this

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

webdevetc profile pic
webdevetc

I'm a late 20's web developer, specialising in Laravel, but work with other PHP frameworks and associated technologies (such as JS). I mostly write about PHP here. Contact me here. Need to hire or work with a contract PHP software developer in London, UK (or freelance)? Contact me and check my availability.

Leave a Comment