We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

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!



14.4k
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....