douxian8883 2009-02-11 11:05
浏览 20
已采纳

跟踪对象状态

In PHP, what's the best way to track an objects state, to tell whether or not it has been modified? I have a repository object that creates new entities, they are then read/modified by other components and eventually given back to the repository. If the object has changed I want the repository to save the data back to the persistent storage (DB).

I can think of four options:

  1. Use an internal boolean property called $_modified, which every setter updates when modifications are made (tedious if there are a lot of setters).
  2. Some horrible ugly hack using serialize() and comparing the strings (I'm sure this is a very bad idea, but I thought I'd add it for completeness)
  3. Something like the above but with a hash of the objects properties (not sure if it would work with objects that contain other objects)
  4. Taking clones of the objects as they come out of the repo and comparing what comes in (more complicated than it sounds, because how do you know which clone to compare the object to?)

    or...

  5. Some other clever trick I'm not aware of?

Thanks,
Jack

  • 写回答

4条回答 默认 最新

  • du131642 2009-02-11 11:11
    关注

    Option 1 - using a boolean flag - is the best way. In terms of performance, as well as general usability and portability.

    All the other options incur excessive overhead which is simply not needed in this case.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教