What is Observer Pattern in Laravel | Know About Obeserver

by Tarun Korat Jun 26, 2024 Total Views: 105

The Observer Design Pattern is a behavioral design pattern establishing a one-to-many relationship between objects. When the state of one object (the subject) changes, all its dependent objects (observers) are automatically notified and updated. This pattern is especially valuable for keeping related objects consistent without tightly coupling them.


In Laravel, the Observer pattern is used to listen to events triggered by Eloquent models. This enables you to handle various model events like creating, created, updating, updated, deleting, and deleted in an organized and clean manner.


Example Use Cases

1.Auto-Generating Slugs:

2.Sending Welcome Emails:

3.Logging User Activity:


When to Use the Observer Pattern


The Observer pattern is ideal when you need to separate concerns and avoid tight coupling between the model and the actions performed on its events. Use the Observer pattern in Laravel when:


  • Decoupling Logic: You want to keep your models clean and free from additional responsibilities.
  • Maintaining Single Responsibility Principle: Each class should have one responsibility, and observers help maintain this principle by handling the event logic separately.
  • Reusability: Observers can be reused across different models or even in different projects.
  • Scalability: As your application grows, it becomes easier to manage and scale with observers handling the logic for model events.


What is the Observer Design Pattern?


The Observer Design Pattern is one of the Gang of Four (GoF) design patterns that promotes loose coupling in software design. It consists of two main components:


  • 1. Subject (Observable): The object that holds the state and sends notifications to observers when its state changes.
  • 2. Observer: The object that needs to be informed about changes in the subject.


How is the Observer Pattern Used in Laravel?


Laravel offers a clean and straightforward way to implement the Observer pattern with Eloquent models. This allows you to maintain clean model code and handle various actions that need to be performed when a model event occurs.


Creating an Observer

To create an observer in Laravel, you can use the make:observer Artisan command:


php artisan make:observer UserObserver --model=User


This command will generate an observer class in the App\Observers directory. The observer will look something like this:


<?php

namespace App\Observers;

use App\Models\User;

class UserObserver
{
    public function creating(User $user)
    {
        // Logic to execute before a user is created
    }

    public function created(User $user)
    {
        // Logic to execute after a user is created
    }

    public function updating(User $user)
    {
        // Logic to execute before a user is updated
    }

    public function updated(User $user)
    {
        // Logic to execute after a user is updated
    }

    public function deleting(User $user)
    {
        // Logic to execute before a user is deleted
    }

    public function deleted(User $user)
    {
        // Logic to execute after a user is deleted
    }
}


Registering the Observer

After creating the observer, you need to register it. This is typically done in the boot method of a service provider, such as AppServiceProvider:


<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Models\User;
use App\Observers\UserObserver;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        User::observe(UserObserver::class);
    }

    public function register()
    {
        //
    }
}


Using Observers in Laravel


Observers are useful in various scenarios, such as:


  • Logging Changes: Track changes to a model’s state for auditing purposes.
  • Sending Notifications: Notify users or other systems about changes to a model.
  • Updating Related Models: Automatically update related models when a change occurs.
  • Enforcing Business Rules: Ensure business rules are followed before or after changes to a model.


Tags: Laravel Patterns Observers PHP

Please login to create comment.

Author
Author Image

"Tarun Korat, an avid wordsmith and passionate storyteller, pours his creativity into every piece he writes. With a knack for weaving engaging narratives, Tarun captivates readers with his insightful perspectives on life, love, and everything in between. Join him on his literary journey as he shares his thoughts and musings through the power of words."

- Tarun Korat
Follow Me: