ronan-gloo / laravel-observer by ronan-gloo

Dispatch Eloquent’s models events to the model’s instance, and / or a specific class
8
5
3
Package Data
Maintainer Username: ronan-gloo
Maintainer Contact: sonotone13@gmail.com (ronan-gloo)
Package Create Date: 2012-10-22
Package Last Update: 2014-09-06
Language: PHP
License: Unknown
Last Refreshed: 2024-11-19 03:23:28
Package Statistics
Total Downloads: 8
Monthly Downloads: 0
Daily Downloads: 0
Total Stars: 5
Total Watchers: 3
Total Forks: 3
Total Open Issues: 0

Laravel Observer

Dispatch Eloquent’s models events to the model’s instance, and / or a specific class

Installation

php artisan bundle:install observer

Events

  • saving: before save
  • saved: after save
  • updated: after update
  • created: after creation
  • deleting: defore delete
  • deleted: after delete

Usage

1. Whithin the model
class Post extends Eloquent {
    
    /**
     * This method will be run after an update or a creation.
     */
    public function event_saved()
    {
        Log::info(get_class($this).' with title "'.$this->title.'" saved');
    }
    
}
2. With an Observer
// The Model
class Post extends Eloquent {
    
    public static $observe = array(
        
        // Single observer for a single event
        'saving' => 'Observe_Slug',
        
        // Multiple observers for a single event
        'created' => array('Observe_Log', 'Observe_Mail'),
        
        // Observer with parameters
        'updated' => array('Observe_History' => array('log' => true))
    );
    
}

// Observer
class Observer_Slug extends Observer\Observe {
    
    // Modelfy object before to save it
    public function saving($model)
    {
        model->slug = Str::slug($model->title);
    }
    
    // event with parameters: parameters from model are instance properties here
    public function updated($model)
    {
        if ($this->log == true)
        {
            Do something...
        }
    }
}