Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

How to avoid the same code at beforeCreate/beforeUpdate

Hi,

how can I avoid the same code a my models beforeCreate and beforeUpdate? I tried to combine booth to beforeSave but that didn't work.

Thanks!



3.9k
Accepted
answer

Solved it using setters. Thanks for your attention. Example:

public function setDate($date) {
    $date = new DateTime($date);
    $this->date = $date->format('Y-m-d');
}

beforeSave should work too. Also you can always call beforeCreate from beforeUpdate :).

edited Jul '16

If you have a complex method which has to be executed for multiple events. For example clearing some cache files, or sending something to different server... You should separate your logic in a common method and request it where needed

private function yourComplexAction()
{
    // Blablabla
}

public function afterSave()
{
    $this->yourComplexAction();
}

public function beforeCreate()
{
    $this->yourComplexAction();
}

public function afterDelete()
{
    $this->yourComplexAction();
}
// e.t.c....