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

Model vs Database : beforeCreate vs trigger

In: Implementing Events in the Model’s class it describes how we can use beforeCreate() and beforeUpdate() in the model to perform setting a timestamp to a created and modified date column.

I currently use database triggers to perform these operations and as a result in the model in the initizlize I write:

$this->skipAttributes(array('created', 'modified'));

I note that if you use database triggers phalcon messaging becomes redundant where database triggers are used over model events.

Are there any really good reasons I should move my database triggers out of the database and translate them into events in the model class.

What are the advantages of using database triggers? Performance?

Is this just a style issue? Or is implementing in the model class a fundamentlal approach which benefits MVC?



125.8k
Accepted
answer

For this situation I think database triggers are the best solution, since you already have them. Technically you are separating model logic from the model code. If anyone other than you looks at the code, it might not be obvious how those columns are being set.

If I was in your situation I'd be inclined to keep the triggers as-is. If I were starting from scratch, I'd probably put the functionality in the model and PHP code. While the triggers are more performant, as you mentioned, often that level of performance isn't necessary so I'd opt for having all my model functionality in one place.