fereydooni/laravel-observable

A robust and feature-rich observation system for dynamically observing Laravel objects

dev-master 2025-04-24 14:16 UTC

This package is auto-updated.

Last update: 2025-04-24 14:19:56 UTC


README

A robust and feature-rich observation system for dynamically observing Laravel objects (models, events, or other objects) and triggering callback functions using PHP attributes.

Installation

You can install the package via composer:

composer require fereydooni/laravel-observable

After installing, publish the configuration file:

php artisan vendor:publish --provider="Fereydooni\LaravelObservable\DynamicObserverServiceProvider"

Run the migrations:

php artisan migrate

Usage

Using Attributes

Observe Attribute

Use the Observe attribute to define observation rules:

use Fereydooni\LaravelObservable\Attributes\Observe;

#[Observe(target: 'App\Models\User', event: 'created', callback: 'App\Services\Logger@log', priority: 10)]
class UserObserver
{
    public function handle($model) 
    {
        // Custom logic when User model is created
    }
}

Observable Attribute

Mark classes or methods as observable:

use Fereydooni\LaravelObservable\Attributes\Observable;

#[Observable(name: 'user_activity')]
class UserService
{
    public function createUser($data)
    {
        // This method can be observed
        return User::create($data);
    }
}

Using the ObservationManager

use Fereydooni\LaravelObservable\ObservationManager;

// Get an instance of the manager
$manager = app(ObservationManager::class);

// Dynamically observe a model
$manager->observe('App\Models\User', 'updated', function($model) {
    \Log::info('User updated: ' . $model->id);
});

// Query observation logs
$logs = $manager->getObservationLogs('App\Models\User');

// Enable/disable specific observation
$manager->toggleObservation('App\Models\User', 'created', false); // Disable
$manager->toggleObservation('App\Models\User', 'created', true);  // Enable

Conditional Observation

use Fereydooni\LaravelObservable\Attributes\Observe;

#[Observe(
    target: 'App\Models\User', 
    event: 'created', 
    callback: 'App\Services\AdminLogger@log',
    condition: 'isAdmin'
)]
class AdminUserObserver
{
    public function isAdmin($model)
    {
        return $model->role === 'admin';
    }
    
    public function handle($model) 
    {
        // This will only trigger for admin users
    }
}

Configuration

The package comes with a configuration file that allows you to:

  • Enable/disable observation globally
  • Set default priority for observations
  • Configure logging backend (database or file)
  • Enable/disable conditional observation

Testing

composer test

License

The MIT License (MIT). Please see License File for more information.