diff --git a/src/Database/Concerns/HasEvents.php b/src/Database/Concerns/HasEvents.php index 8de1becc0..ef76fee1b 100644 --- a/src/Database/Concerns/HasEvents.php +++ b/src/Database/Concerns/HasEvents.php @@ -55,6 +55,15 @@ protected function bootNicerEvents() static::$eventsBooted[$class] = true; } + /** + * initializeModelEvent is called every time the model is constructed. + */ + protected function initializeModelEvent() + { + $this->fireEvent('model.afterInit'); + $this->afterInit(); + } + /** * flushEventListeners removes all of the event listeners for the model * Also flush registry of models that had events booted @@ -104,8 +113,7 @@ public static function fetched($callback) } /** - * afterBoot is called after the model is constructed, a nicer version - * of overriding the __construct method. + * afterBoot is called after the model is constructed for the first time. */ protected function afterBoot() { @@ -122,6 +130,25 @@ protected function afterBoot() */ } + /** + * afterInit is called after the model is constructed, a nicer version + * of overriding the __construct method. + */ + protected function afterInit() + { + /** + * @event model.afterInit + * Called after the model is initialized + * + * Example usage: + * + * $model->bindEvent('model.afterInit', function () use (\October\Rain\Database\Model $model) { + * \Log::info(get_class($model) . ' has initialized'); + * }); + * + */ + } + /** * beforeCreate handles the "creating" model event */ diff --git a/src/Database/Model.php b/src/Database/Model.php index 9ad899b18..2f165a989 100644 --- a/src/Database/Model.php +++ b/src/Database/Model.php @@ -61,6 +61,8 @@ public function __construct(array $attributes = []) $this->extendableConstruct(); + $this->initializeModelEvent(); + $this->fill($attributes); } @@ -530,5 +532,7 @@ public function __wakeup() $this->bootNicerEvents(); $this->extendableConstruct(); + + $this->initializeModelEvent(); } } diff --git a/src/Database/Traits/SortableRelation.php b/src/Database/Traits/SortableRelation.php index 3518ca646..f54e8baae 100644 --- a/src/Database/Traits/SortableRelation.php +++ b/src/Database/Traits/SortableRelation.php @@ -32,6 +32,10 @@ trait SortableRelation */ public function initializeSortableRelation() { + $this->bindEvent('model.afterInit', function() { + $this->defineSortableRelations(); + }); + $this->bindEvent('model.relation.attach', function ($relationName, $attached, $data) { if (!array_key_exists($relationName, $this->getSortableRelations())) { return; @@ -45,8 +49,6 @@ public function initializeSortableRelation() $this->$relationName()->updateExistingPivot($id, [$column => ++$order]); } }); - - $this->defineSortableRelations(); } /**