From 1efddf416e559a833febe7f5bf7a919aad9f527d Mon Sep 17 00:00:00 2001 From: Toby Zerner Date: Tue, 22 Sep 2015 17:22:25 +0930 Subject: [PATCH] Add API to run callback after a model instance is saved --- framework/core/CHANGELOG.md | 1 + framework/core/src/Core/Model.php | 34 +++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/framework/core/CHANGELOG.md b/framework/core/CHANGELOG.md index ae1f12568..3a8586e08 100644 --- a/framework/core/CHANGELOG.md +++ b/framework/core/CHANGELOG.md @@ -12,6 +12,7 @@ This project adheres to [Semantic Versioning](http://semver.org/). - `route` attribute for Mithril elements as a shortcut to link to a route. - Abstract SettingsModal component for quickly building admin config modals. - "Debug" button to inspect the response of a failed AJAX request. +- `Model::afterSave()` API to run callback after a model instance is saved. ### Changed - Migrations must be namespaced under `Flarum\Migrations\{Core|ExtensionName}`. ([#422](https://github.com/flarum/core/issues/422)) diff --git a/framework/core/src/Core/Model.php b/framework/core/src/Core/Model.php index aa1f3ebb4..8420439a2 100755 --- a/framework/core/src/Core/Model.php +++ b/framework/core/src/Core/Model.php @@ -35,6 +35,29 @@ abstract class Model extends Eloquent */ public $timestamps = false; + /** + * An array of callbacks to be run once after the model is saved. + * + * @var callable[] + */ + public $afterSaveCallbacks = []; + + /** + * {@inheritdoc} + */ + public static function boot() + { + parent::boot(); + + static::saved(function (Model $model) { + foreach ($model->afterSaveCallbacks as $callback) { + $callback($model); + } + + $model->afterSaveCallbacks = []; + }); + } + /** * Get the attributes that should be converted to dates. * @@ -94,6 +117,17 @@ abstract class Model extends Eloquent ); } + /** + * Register a callback to be run once after the model is saved. + * + * @param callable $callback + * @return void + */ + public function afterSave($callback) + { + $this->afterSaveCallbacks[] = $callback; + } + /** * @inheritdoc */