Last active
April 11, 2017 23:10
-
-
Save ninjapanzer/bc746692c3a6dcb8b64935abaf8eebc1 to your computer and use it in GitHub Desktop.
Laravel ModelEventHookTrait
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Adds a cleaner default mechanism for adding saved and created handler functions in laravel with a way to control event bubbling