Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating database on __destruct()?

Tags:

php

destructor

Do you think it's a good idea?

Let's say you have an application component that is used by other components to retrieve / update data in the db. It's basically a class with get(), set(), update() methods.

Would it be a good idea for that component to update (or set) data only in it's properties when called, and on __destruct to update the db as well? Or should it directly update the db on each set/ update call ?

like image 485
thelolcat Avatar asked Feb 29 '12 14:02

thelolcat


2 Answers

Updating the database on object destruction smells to me a little bit like a software side effect. That is, an action that takes place in an unexpected and somewhat non-explicit place. It would not be obvious from viewing your code that a database action is happening when __destruct() is called, even if you call it explicitly. Future code maintainers (including yourself) could be easily confused when trying to hunt down a bug involving inconsistent data, but not seeing any calls to the database or method calls resembling data interactions when viewing the code.

I would advise against it.

like image 59
Michael Berkowski Avatar answered Nov 17 '22 09:11

Michael Berkowski


Attempting to throw an exception from a destructor (called in the time of script termination) causes a fatal error.

So what about when you have an exception? Any way, I think this is not a good idea, you can't control the work flow, and it is easy to lead a debug hell.

like image 2
xdazz Avatar answered Nov 17 '22 08:11

xdazz