Skip to content

Instantly share code, notes, and snippets.

@ninjapanzer
Last active April 11, 2017 23:10
Show Gist options
  • Save ninjapanzer/bc746692c3a6dcb8b64935abaf8eebc1 to your computer and use it in GitHub Desktop.
Save ninjapanzer/bc746692c3a6dcb8b64935abaf8eebc1 to your computer and use it in GitHub Desktop.
Laravel ModelEventHookTrait
<?php namespace App;
trait ModelEventHookTrait
{
protected static function createdHook()
{
return function ($model_instance) {
if (method_exists(__CLASS__, 'createdHandler')) {
self::createdHandler($model_instance);
}
};
}
protected static function savedHook()
{
return function ($model_instance) {
if (method_exists(__CLASS__, 'savedHandler')) {
self::savedHandler($model_instance);
}
};
}
protected static function withoutEvents(\Closure $callback)
{
self::unsetEventDispatcher();
$callback();
self::setEventDispatcher(new \Illuminate\Events\Dispatcher);
}
}
<?php namespace app;
use Illuminate\Database\Eloquent\Model;
class Entity extends Model
{
use ModelEventHookTrait;
public static function boot()
{
parent::boot();
self::created(self::createdHook());
self::saved(self::savedHook());
}
private static function savedHandler($entity)
{
$entity->handleEvent();
}
private static function createdHandler($entity)
{
// Callback will run without dispatch registered
self::withoutEvents(function () use ($entity) {
$entity->attribute = 10;
// Will not trigger another Saved Handler Event
$entity->save();
});
}
}
@ninjapanzer
Copy link
Author

Adds a cleaner default mechanism for adding saved and created handler functions in laravel with a way to control event bubbling

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment