🎉 Hooray! After 3 years of work, I've finally released the ebook on design patterns! Check it out »

Composite in PHP

Composite is a structural design pattern that allows composing objects into a tree-like structure and work with the it as if it was a singular object.

Composite became a pretty popular solution for the most problems that require building a tree structure. Composite’s great feature is the ability to run methods recursively over the whole tree structure and sum up the results.

Usage of the pattern in PHP



Usage examples: The Composite pattern is commonly used when working with object trees. The simplest example would be applying the pattern to elements of the DOM tree, working with the composite and simple elements of the tree in the same way.

Identification: If you have an object tree, and each object of a tree is a part of the same class hierarchy, this is most likely a composite. If methods of these classes delegate the work to child objects of the tree and do it via the base class/interface of the hierarchy, this is definitely a composite.

Composite in Other Languages

Design Patterns: Composite in Java Design Patterns: Composite in C# Design Patterns: Composite in C++ Design Patterns: Composite in Python Design Patterns: Composite in Ruby Design Patterns: Composite in Swift Design Patterns: Composite in TypeScript