Skip to content

Instantly share code, notes, and snippets.

@MuhammadQuran17
Last active October 9, 2025 05:47
Show Gist options
  • Select an option

  • Save MuhammadQuran17/28e87b5be8e30a5d9dab8497a4df03bf to your computer and use it in GitHub Desktop.

Select an option

Save MuhammadQuran17/28e87b5be8e30a5d9dab8497a4df03bf to your computer and use it in GitHub Desktop.
OOP-Patterns

Observer and Pub/Sub pattern

While the terms are often used interchangeably, there is a technical distinction:

Publisher-subscriber is a network oriented architectural pattern and Observer is an object-event oriented pattern. They both are used at different Software levels.

Observer pattern: The subject (event) directly manages and notifies its observers (listeners). It's typically implemented within a single application process or codebase.

Publish-Subscribe pattern: Publishers and subscribers do not know each other. They communicate through a third component, typically a message broker or "event bus." Pub/Sub is better suited for cross-application communication, where different services or processes are involved.

Since Laravel's event system dispatches and handles events internally using its own dispatcher, the Observer pattern is the most direct and accurate description for Event/Listeners.

Transformers - Adapter pattern, and Mappers - Data mapper pattern

Data Retrieval: You might use a Data Mapper pattern (or an ORM like Eloquent) to retrieve raw data from the database and populate a User model. It handles the mapping between your database table and the User model for you. The User::find() call handles the database interaction. It implicitly maps the retrieved database row into an object with properties corresponding to the table's columns.

Data Transformation: Before sending the data to an API client, you use a Transformer that acts as an Adapter to convert the User model into a UserDto or JSON structure.

Eloquent ORM (as an Active Record pattern)

Repository pattern

namespace App\Repositories;

use App\Contracts\UserRepositoryInterface;
use App\Models\User;

class EloquentUserRepository implements UserRepositoryInterface
{
    public function find(int $id): ?User
    {
        return User::find($id);
    }

    public function all(): array
    {
        return User::all()->toArray();
    }
}

// In a service provider like AppServiceProvider.php
public function register()
{
    $this->app->bind(
        \App\Contracts\UserRepositoryInterface::class,
        \App\Repositories\EloquentUserRepository::class
    );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment