Updating database on __destruct()?

时间秒杀一切 提交于 2019-12-01 04:07:00

问题


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 ?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/9500595/updating-database-on-destruct

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!