> For the complete documentation index, see [llms.txt](https://al-mamun.gitbook.io/al-mamun/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://al-mamun.gitbook.io/al-mamun/design-patterns/composite-pattern.md).

# 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

```
Component
 ├── Leaf
 └── Composite
```

| 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

```
interface MenuComponent
{
    public function render(): string;
}
```

***

## Step 2: Leaf Class

Single menu item.

```
class MenuItem implements MenuComponent
{
    protected string $name;

    public function __construct(string $name)
    {
        $this->name = $name;
    }

    public function render(): string
    {
        return "<li>{$this->name}</li>";
    }
}
```

***

## Step 3: Composite Class

Menu group containing children.

```
class MenuGroup implements MenuComponent
{
    protected string $name;

    protected array $children = [];

    public function __construct(string $name)
    {
        $this->name = $name;
    }

    public function add(MenuComponent $component)
    {
        $this->children[] = $component;
    }

    public function render(): string
    {
        $html = "<ul><strong>{$this->name}</strong>";

        foreach ($this->children as $child) {
            $html .= $child->render();
        }

        $html .= "</ul>";

        return $html;
    }
}
```

***

## Step 4: Usage

```
$dashboard = new MenuItem('Dashboard');
$users = new MenuItem('Users');
$settings = new MenuItem('Settings');

$adminMenu = new MenuGroup('Admin Menu');

$adminMenu->add($dashboard);
$adminMenu->add($users);
$adminMenu->add($settings);

echo $adminMenu->render();
```

***

## Output

```
<ul>
    <strong>Admin Menu</strong>
    <li>Dashboard</li>
    <li>Users</li>
    <li>Settings</li>
</ul>
```

***

## Nested Composite Example

Composite can contain another composite.

```
$reportsMenu = new MenuGroup('Reports');

$reportsMenu->add(new MenuItem('Sales Report'));
$reportsMenu->add(new MenuItem('User Report'));

$adminMenu->add($reportsMenu);

echo $adminMenu->render();
```

***

## Result Structure

```
Admin Menu
 ├── Dashboard
 ├── Users
 ├── Settings
 └── Reports
      ├── Sales Report
      └── User Report
```

***

## Advantages

### 1. Treats Single & Group Objects Uniformly

You can call:

```
->render()
```

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.
