开发者

Object constructors and unique IDs

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 MySQ开发者_高级运维L 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 :-)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜