> 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/observer-pattern.md).

# Observer Pattern

The **Observer Pattern** is a Behavioral Design Pattern where one object (Subject) notifies multiple dependent objects (Observers) automatically whenever its state changes.

It follows a **one-to-many relationship**.

***

## Simple Definition

> When one object changes, all subscribed objects get notified automatically.

***

## Real-Life Example

Think about a YouTube channel:

When a creator uploads a new video:

* Subscribers receive notifications
* Email alerts are sent
* Mobile push notifications appear

```
YouTube Channel → Subscribers
```

The channel is the **Subject**, and subscribers are the **Observers**.

***

## Why Use Observer Pattern?

Without Observer Pattern:

```
class OrderService {

    public function placeOrder()
    {
        // send email
        // send SMS
        // update inventory
        // create invoice
        // push notification
    }
}
```

### Problems

❌ Tightly coupled code\
❌ Difficult to maintain\
❌ Hard to extend\
❌ One class handles everything

***

## Observer Pattern Structure

```
Subject
   ↓
Observers
```

***

## Real-World Use Cases

✅ Event systems\
✅ Notifications\
✅ Real-time updates\
✅ Laravel Events & Listeners\
✅ Stock market systems\
✅ Chat applications

***

## Example: Order Notification System

When an order is placed:

* Send Email
* Send SMS
* Send Push Notification

***

## Step 1: Create Observer Interface

```
interface Observer
{
    public function update($message);
}
```

All observers must implement this method.

***

## Step 2: Create Concrete Observers

### Email Notification Observer

```
class EmailNotification implements Observer
{
    public function update($message)
    {
        echo "Email Sent: {$message}\n";
    }
}
```

***

### SMS Notification Observer

```
class SMSNotification implements Observer
{
    public function update($message)
    {
        echo "SMS Sent: {$message}\n";
    }
}
```

***

### Push Notification Observer

```
class PushNotification implements Observer
{
    public function update($message)
    {
        echo "Push Notification: {$message}\n";
    }
}
```

***

## Step 3: Create Subject Class

The Subject manages observers.

```
class Order
{
    protected $observers = [];

    // Attach observer
    public function attach(Observer $observer)
    {
        $this->observers[] = $observer;
    }

    // Notify all observers
    public function notify($message)
    {
        foreach ($this->observers as $observer) {
            $observer->update($message);
        }
    }

    // Business logic
    public function placeOrder()
    {
        echo "Order Placed Successfully\n";

        $this->notify("New Order Created");
    }
}
```

***

## Step 4: Use Observer Pattern

```
$order = new Order();

$order->attach(new EmailNotification());
$order->attach(new SMSNotification());
$order->attach(new PushNotification());

$order->placeOrder();
```

***

## Output

```
Order Placed Successfully

Email Sent: New Order Created
SMS Sent: New Order Created
Push Notification: New Order Created
```

***

## Full Working Example

```
<?php

interface Observer
{
    public function update($message);
}

class EmailNotification implements Observer
{
    public function update($message)
    {
        echo "Email Sent: {$message}\n";
    }
}

class SMSNotification implements Observer
{
    public function update($message)
    {
        echo "SMS Sent: {$message}\n";
    }
}

class PushNotification implements Observer
{
    public function update($message)
    {
        echo "Push Notification: {$message}\n";
    }
}

class Order
{
    protected $observers = [];

    public function attach(Observer $observer)
    {
        $this->observers[] = $observer;
    }

    public function notify($message)
    {
        foreach ($this->observers as $observer) {
            $observer->update($message);
        }
    }

    public function placeOrder()
    {
        echo "Order Placed Successfully\n";

        $this->notify("New Order Created");
    }
}

$order = new Order();

$order->attach(new EmailNotification());
$order->attach(new SMSNotification());
$order->attach(new PushNotification());

$order->placeOrder();
```

***

## Observer Pattern Flow

```
Order Placed
      ↓
Subject Notifies Observers
      ↓
Email Sent
SMS Sent
Push Notification Sent
```

***

## Advantages

### ✅ Loose Coupling

Subject does not know observer details.

***

### ✅ Easy to Extend

Add new observers easily.

```
class SlackNotification implements Observer
{
    public function update($message)
    {
        echo "Slack Alert: {$message}";
    }
}
```

***

### ✅ Event-Driven Architecture

Perfect for scalable systems.

***

### ✅ Reusable Components

Observers are reusable across applications.

***

## Disadvantages

❌ Too many observers can slow the system\
❌ Debugging becomes difficult in complex event chains\
❌ Notification order may matter sometimes

***

## Real Laravel Examples

| Laravel Feature    | Observer Pattern |
| ------------------ | ---------------- |
| Events & Listeners | User Registered  |
| Model Observers    | created, updated |
| Notifications      | Mail/SMS         |
| Broadcasting       | Real-time events |

Laravel has built-in Observer and Event systems.

***

## Laravel Observer Example

### Create Observer

```
php artisan make:observer UserObserver --model=User
```

***

### Observer Class

```
class UserObserver
{
    public function created(User $user)
    {
        Mail::to($user)->send(
            new WelcomeMail($user)
        );
    }
}
```

***

## Register Observer

```
User::observe(UserObserver::class);
```

***

## When to Use Observer Pattern

Use when:

✅ Multiple systems react to one event\
✅ Event-driven architecture needed\
✅ Loose coupling required\
✅ Notifications are involved

***

## When NOT to Use

❌ Very simple systems\
❌ Only one dependent action exists\
❌ Performance-critical synchronous operations

***

## Observer vs Strategy Pattern

| Observer                   | Strategy               |
| -------------------------- | ---------------------- |
| One-to-many notifications  | One selected algorithm |
| Event-driven               | Behavior-driven        |
| Multiple listeners         | Single strategy        |
| Subject notifies observers | Context uses strategy  |
