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

webdevetc profile pic
webdevetc

I am a 29 year old freelance backend web developer from London, mostly focusing on PHP and Laravel lately. This is my site - I mostly write about PHP here. Contact me here (especially for any contracting jobs early 2019 in London ;) ).

Leave a Comment