For the complete documentation index, see llms.txt. This page is also available as Markdown.

Composite Pattern

The Composite Pattern is a structural design pattern that lets you treat individual objects and groups of objects in the same way.

It is useful for representing tree-like structures such as:

  • File systems

  • Menu systems

  • Categories & subcategories

  • Organization hierarchy

  • Comments & replies


Real Life Example

Think about a Folder System:

Root Folder
 ├── Images
 │    ├── photo1.png
 │    └── photo2.png
 └── Documents
      └── cv.pdf

A folder can contain:

  • Files

  • Other folders

Both are treated similarly.

This is Composite Pattern.


Structure

Part
Responsibility

Component

Common interface

Leaf

Single object

Composite

Group of objects


Laravel / PHP Example

Scenario

We are building a menu system:

  • Menu Item

  • Menu Group

Both should render similarly.


Step 1: Component Interface


Step 2: Leaf Class

Single menu item.


Step 3: Composite Class

Menu group containing children.


Step 4: Usage


Output


Nested Composite Example

Composite can contain another composite.


Result Structure


Advantages

1. Treats Single & Group Objects Uniformly

You can call:

on both:

  • MenuItem

  • MenuGroup


2. Simplifies Tree Structures

Perfect for:

  • Nested menus

  • Category trees

  • Comments

  • Organization hierarchy


3. Easy to Extend

Add new component types without changing existing code.


Real Laravel Use Cases

Use Case
Example

Categories

Parent & child categories

Comments

Nested replies

Menus

Multi-level sidebar

Permissions

Role hierarchy

File System

Files & folders


Composite vs Decorator

Composite
Decorator

Builds tree structures

Adds behavior dynamically

Parent-child relationship

Wrapper relationship

Handles groups

Enhances single object


When to Use Composite Pattern

Use Composite Pattern when:

✅ Objects form tree structures ✅ You need recursive hierarchy ✅ Individual and grouped objects behave similarly ✅ You want cleaner recursive operations


Short Interview Definition

The Composite Pattern allows treating individual objects and groups of objects uniformly using a tree structure.

Last updated