开发者

Is it OK to embed database object?

I have the following data tables: users, user_pictures, messages,开发者_如何学Python forum. To outline it's structure:

forum
users
 user_pictures
 messages

since if no users, no user_pictures neither messages. Now I want to this structured logic to be build in my classes. I use a standalone class for each tables to do the actions according to the table. Normally it would look like this:

$forum = new Forum();

$users = new User();

$messages = new Message();

$user_pictures = new User_picture();

but what if if I create messages and user_pictures in the constructor of users? And it's reference would be there too. Is it OK?


but what if if I create messages and user_pictures in the constructor of users?

You should not create anything in the ctor. That would be doing work in the ctor and its also mixing creation graph with collaborator graph. If you want to assemble a complex object graph, use a Builder or a Factory pattern. If you need to create something in a collaborator, pass an instance of a factory or builder to the collaborator. But dont do work in a constructor.

As for the remainder of your question: this can be answered the same as your previous question. Use a custom DataMapper and/or Repository and/or an ORM. Dont model your classes after your RDBMS structure.


Your logic will depend on what $messages and $user_pictures really is. Are they the messages and pictures for that user only or are they the forums'?

If it's the first case, then $messages and $user_pictures should sub class $user as they are associated with that class. If it's the later, then they should sub class $forum. If they are unrelated, then they should all be their own classes.

If you're gonna sub class $users with $messages and $user_pictures, I would create a method on the user object to access those sub classes. Something like $user->get_messages to get the messages associated with that user, same for user pictures.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜