简体   繁体   中英

Facebook-like wall

I'm currently working on social network project created from scratch. I need to create a wall that shows user's and his friends' messages and comments along with 'likes' and attachments. Currently likes, attachments and comments returned in loops for each message:

foreach ($messages as $message) {
    $message->get_likes();
    $message->get_comments();
    ...
} 

that is lead to huge number of queries. at least extra 3 for every message having minimum 15 messages on the wall-page. so i want to reduce the number of queries by creating more complex queries and merging them on programm level like this:

$arr = array();
        foreach ($messages as $message) {
            $arr[$message->id] = $message->as_array();
            $arr[$message->id]['comment'] = array();
            foreach ($comments as $comment) {
                if ($comment->message_id == $message->id) {
                    $arr[$message->id]['comment'][$comment->id] = $comment->as_array();
                }
            }

it looks ugly and complicated especially assuming that i also need to get likes and attachments in a such way. so is there's any better idea how to handle this?

I don't see a problem with that. I'm currently working on the same thing and that is almost exactly what I do for retrieving comments. I haven't thought of how I want to do the "Likes" yet. I probably won't call it "Like" because I don't want to totally copy facebook.

There are many possible ways to approach this. Listing some of the few,

Smart database design

Look at the way facebook shows messages. Not all the comments of all the messages are shown. What you could do is add an additional column in messages table that maintains the comment count and another for likes count. This allows you to show messages with comment count and on click, use ajax to load the comments.

Caching

Most websites have 95%+ reads. So caching at multiple levels in the application is always a way to reduce the load on the database. Use a solution such as memcache to store the multi-query result for messages or go as far as storing the entire wall in cache.

Different way to store data

You could try any of the NoSQL solutions that provide very fast key lookups, which is what most of messages, likes and comments are. Also see - How FriendFeed uses MySQL to store schema-less data

Perhaps using a combination of these approaches is the way to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM