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 committed Jul 27, 2016
1 parent e52a3f9 commit 8911c53
Showing 1 changed file with 85 additions and 1 deletion.
86 changes: 85 additions & 1 deletion src/Http/Controllers/EloquentController.php
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,47 @@ 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();

if ($result) {
$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) {
$this->updating($model);
} else {
$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) {
$this->updated($model);
} else {
$this->created($model);
}
}

/**
Expand Down Expand Up @@ -350,4 +390,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 8911c53

Please sign in to comment.