dsbiw2911188 2011-02-16 13:16
浏览 73
已采纳

对象构造函数和唯一ID

I'm getting my feet wet in OOP and have a question about __construct() content:

Suppose I want to make a PlayResult class, which will take protected ID,Date, and Winner properties. That would seem like logical things to put in the __construct() method, but the ID is the unique auto-incremented ID generated by MySQL when the play result is added to the table for the first time.

Now the ID is very important to my code, because that's how I keep track of individual records when they're being edited. However, obviously when a user uses an HTML form to submit a new play result there is no ID value because the result has not yet entered the database.

So, should the ID go in the constructor or not? Or should I construct with date and winner only, then set the ID if I have one?

Thanks :-)

  • 写回答

1条回答 默认 最新

  • dppcyt6157 2011-02-16 13:35
    关注

    Saving the object in the database is not the responsibility of the object (unless it's an ActiveRecord), but of a class on the persistence layer, for instance a Table Data Gateway. As such, the PlayResult class should not have to bother about the ID being set or not and be an optional field.

    If you want the ID to be required in the object, you'd have to check if it exists in the database (cf. Repository or Identity Field). If not, create the new record in the database first, then create the object instance of the PlayResult with the newly created ID.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗