开发者

Suggestions on implementing PHP object between database

Here is something I would like to do:

User:
id
first_name
second_name
gender

and I make a php Object "User", and I modify the "User"'s attribute, I update the database, for example,

$aUser->setGender("M");

in the set gender, I execute an update statement using php... But I got a problems here, if the user only have 4 attributes, it is ok for me to write one by one. But if the object have many attributes, I need to write more update statement....(I can write a general update statement, whatever I change开发者_如何学C which attribute, I update all the attribute once, but I think it is no point to do so.. ... ) How can I simplify that? Thank you.


The comments of the question suggests it: You should use a method like save() from time to time, instead of querying the database every time anything changes.

Personally I don't see a problem in updating every column, even if the corresponding property didn't changed. However, you can save the original values in another (array) property and then compare the values against each other.


You could have a function like the following (similar to what others are suggesting):

$aUser->setValues(array("gender" => "M", "first_name" => "Steve"));

Then that function can reference your object variables to check and see if they're different and run the update. Or just run the update with the same values.


Don't reinvent the wheel. Use an object relational mapper. What you're doing sounds like it would be served best by RedBean.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜