Skip to content

Commit

Permalink
Before & After commit hooks
Browse files Browse the repository at this point in the history
Adds callbacks for creating/created/updating/updated models on a
controller.

Callbacks can be defined in controllers that inherit the
`EloquentController`.

``php
class UsersController extends EloquentController
{
    protected function creating(Model $model)
    {
        // Before the model is created.
    }

    protected function created(Model $model)
    {
        // After the model has been created.
    }

    protected function updating(Model $model)
    {
        // Before the model is updated.
    }

    protected function updated()
    {
        // After the model has been created.
    }
}
``

---

See #11 for a bit more discussion.`
  • Loading branch information
Josh Taylor authored and josh-taylor committed Jul 26, 2016
1 parent e52a3f9 commit 5e11231
Showing 1 changed file with 83 additions and 1 deletion.
84 changes: 83 additions & 1 deletion src/Http/Controllers/EloquentController.php
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,45 @@ protected function hydrate(ResourceInterface $resource, Model $model)
*/
protected function commit(Model $model)
{
return $model->save();
$isUpdating = $model->exists;

$this->beforeCommit($model, $isUpdating);

$result = $model->save();

$this->afterCommit($model, $isUpdating);

return $result;
}

/**
* Determines which callback to use before creating or updating a model.
*
* @param Model $model
* @param bool $isUpdating
*/
protected function beforeCommit(Model $model, $isUpdating)
{
if ($isUpdating) {
return $this->updating($model);
}

return $this->creating($model);
}

/**
* Determines which callback to use after a model is updated or created.
*
* @param Model $model
* @param bool $isUpdating
*/
protected function afterCommit(Model $model, $isUpdating)
{
if ($isUpdating) {
return $this->updated($model);
}

return $this->created($model);
}

/**
Expand Down Expand Up @@ -350,4 +388,48 @@ private function doDestroy(Model $model)
return $this->destroy($model);
});
}

/**
* Called before the model is created.
*
* Child classes can overload this method if they need to do any logic pre-creation.
*
* @param Model $model
*/
protected function creating(Model $model)
{
}

/**
* Called after the model has been created.
*
* Child classes can overload this method if they need to do any logic post-creation.
*
* @param Model $model
*/
protected function created(Model $model)
{
}

/**
* Called before the model is updated.
*
* Child classes can overload this method if they need to do any logic pre-updating.
*
* @param Model $model
*/
protected function updating(Model $model)
{
}

/**
* Called after the model has been updated.
*
* Child classes can overload this method if they need to do any logic post-updating.
*
* @param Model $model
*/
protected function updated(Model $model)
{
}
}

0 comments on commit 5e11231

Please sign in to comment.