mongodb 社交网站_使用PHP,MongoDB和jQuery进行社交网络样式发布-第2部分

mongodb 社交网站

In the previous part of the series, we explained the database architecture, post stream design and application flow required for developing our post mechanism wherein the user will be able to post a status, like/unlike other people's statuses and comment on them. This part of the series will drive you through the coding required to implement these functionalities. We will use the application flow and database structure as discussed in the last article. Don't forget to download the code from the github repo if you'd like to follow along.

在本系列前一部分中 ,我们解释了开发我们的发布机制所需的数据库体系结构,发布流设计和应用程序流程,其中用户将能够发布状态,就像/不像其他人的状态一样,并对其进行评论。 本系列的这一部分将引导您完成实现这些功能所需的编码。 我们将使用上一篇文章中讨论的应用程序流和数据库结构。 如果您想继续,请不要忘记从github存储库下载代码。

插入帖子: (Insert Post:)

In our index.php file, we had added a Create New Post button. Clicking it will call a JavaScript function new_post with the user id from the session as its parameter.

在我们的index.php文件中,我们添加了一个Create New Post按钮。 单击它会调用一个JavaScript函数new_post ,并将会话中的用户ID作为其参数。

<input type="button" value="Create New Post" id="btn_new_post" 
onClick="new_post('<?php echo $_SESSION['user_id']; ?>')" class="button_style"/>

Referring to the code in script.js, let us understand the function new_post step-by-step:

参考script.js的代码,让我们逐步了解new_post函数:

We first get the post text in a variable new_post_text and check if this text is empty using JavaScript's trim function. If the text is empty, we show an alert message to enter the post text.

我们首先在变量new_post_text获取帖子文本,然后使用JavaScript的trim函数检查该文本是否为空。 如果文本为空,我们将显示一条警告消息以输入帖子文本。

function new_post(user_session_id) 
{    
    var new_post_text = $('#post_textarea').val();
    if(!$.trim(new_post_text))
    {
        alert("Please enter some text in the post");
           return;    
    }

We then send an AJAX POST request using jQuery’s $.POST function:

然后,我们使用jQuery的$.POST函数发送AJAX POST请求:

$.post('php_scripts/insert_new_post.php',{
     user_id: user_session_id,
post_text: new_post_text
},function(output){
         // code to be executed after success of AJAX call
    });

The format of jQuery’s $.POST function is:

jQuery的$.POST函数的格式为:

jQuery.post(url,{parameter:value}, success(output){ //function body });

The first parameter is the url of the file to be called. The second parameter is list of parameters to be sent to the url. The third parameter is a callback function that is executed if the AJAX request succeeds. The variable output contains the output received from the called file.

第一个参数是要调用的文件的URL。 第二个参数是要发送到url的参数列表。 第三个参数是一个回调函数,如果AJAX请求成功,则执行该回调函数。 变量输出包含从调用文件接收的输出。

So, in our case we are calling insert_new_post.php, while passing user id and post text as parameters. We will get back to this function later to write the code inside the callback function.

因此,在本例中,我们在调用insert_new_post.php同时传递用户ID和发布文本作为参数。 稍后我们将回到此函数以在回调函数中编写代码。

Next, open the file insert_new_post.php in the php_scripts folder. This is the file wherein we will write the code that interacts with the database. First of all, we create a new post id using new MongoId(). We then get the user id and post text passed from the JS function using the $_POST superglobal. As you might know, a MongoID is a combination of time and other parameters. We fetch the creation time of the post using post_id and the getTimestamp function. We will be using this timestamp as the creation time of our post.

接下来,在php_scripts文件夹中打开文件insert_new_post.php 。 这是我们将在其中编写与数据库交互的代码的文件。 首先,我们使用new MongoId()创建一个新的帖子ID。 然后,我们获取用户ID,并使用$_POST超全局变量发布从JS函数传递的文本。 您可能知道, MongoID是时间和其他参数的组合。 我们使用post_idgetTimestamp函数获取帖子的创建时间。 我们将使用此时间戳作为帖子的创建时间。

$post_id = new MongoId();
$user_id = new MongoId($_POST['user_id']);
$user_session_id = new MongoId($_SESSION['user_id']);
$post_text = $_POST['post_text'];
$timestamp=date('D, d-M-Y', $post_id->getTimestamp());

Then, we check if the user id received through the AJAX request is same as the current session's user id. This is just a small check to confirm that the file is called from the correct source – we don't want a user performing the actions for someone else. We then create a document containing all the post elements and execute an insert function with the same.

然后,我们检查通过AJAX请求接收的用户ID是否与当前会话的用户ID相同。 这只是一小项检查,以确认是否从正确的源调用了该文件–我们不希望用户为其他人执行操作。 然后,我们创建一个包含所有post元素的文档,并使用相同的元素执行insert函数。

if($user_id == $user_session_id)
{
    $collection = $database->selectCollection('posts_collection');
    $new_post_mongo = array ( '_id'=> $post_id,
                              'post_author_id' => $_SESSION['user_id'],
                              'post_text' => $post_text,
                              'total_likes' => 0,
                              'likes_user_ids' => array (),
                              'comments' => array (),
                              'total_comments' => 0,
                              'timestamp'=>$timestamp
                            );
    $collection->insert($new_post_mongo);                          
}

Once the new document is inserted into the database, we have to show the newly inserted post on our index page. For this we will create and send HTML content from here, and this output will be received as output by the jQuery function new_post which called this page. The code to generate this HTML is similar to what we did to display each post on the home stream in the previous article. So, I am skipping this part of explaining the same code again here. You can refer to the code after query insertion in insert_new_post.php.

将新文档插入数据库后,我们必须在索引页面上显示新插入的帖子。 为此,我们将从此处创建并发送HTML内容,此输出将由jQuery函数new_post调用此页面作为输出接收。 生成此HTML的代码类似于我们在上一篇文章中的主页流上显示每个帖子的操作。 因此,我在这里跳过了再次解释相同代码的部分。 您可以在插入查询后在insert_new_post.php引用该代码。

Going back to the jQuery function new_post, let us modify the post success logic inside the callback. Here, we prepend the output received to the existing post stream using the prepend method and then display it using jQuery hide and slideDown animation. Lastly, we clear all the existing content of the post textarea.

回到jQuery函数new_post ,让我们修改回调内部的成功发布逻辑。 在这里,我们使用prepend方法将接收到的输出添加到现有的post流中,然后使用jQuery hideslideDown动画显示它。 最后,我们清除发布文本区域的所有现有内容。

$.post(insert_new_post_filename,{
    user_id: user_session_id,
    post_text: new_post_text},function(output){
               $('#post_stream').prepend(output);
    var new_post_id=$("#post_stream div:first-child").attr("id");
    $("#"+new_post_id).hide().slideDown();
    $('#post_textarea').val(null);
});

That’s all. We are done with the whole process of inserting a new post and displaying it back on our index page without refreshing the whole page. Let us now quickly see a similar process for liking/unliking the posts.

就这样。 我们已经完成了插入新帖子并在不刷新整个页面的情况下将其显示在索引页面上的整个过程。 现在让我们快速查看喜欢/取消喜欢这些帖子的类似过程。

喜欢/不喜欢的帖子: (Like/Unlike Posts:)

Locate the span for displaying the Like/Unlike label in index.php. Add an onclick function call post_like_unlike with the current session user id as its parameter.

index.php找到显示“ 喜欢/不喜欢”标签的范围。 添加一个onclick函数调用post_like_unlike ,以当前会话用户ID作为其参数。

<span class="post_feedback_like_unlike" id="<?php echo $post_like_unlike_id;?>"  
onclick="post_like_unlike(this,'<?php echo $_SESSION['user_id']; ?>')">
    <?php echo $like_or_unlike; ?>
</span>

In this JS function, we will first check whether the user has clicked Like or Unlike. For this, we grab the HTML text (Like/Unlike) of the span element declared above using the id property of post_id_like_unlike received as the parameter. Here, type will contain the text Like or Unlike.

在这种JS功能,我们会先检查用户是否点击相同的或不同 。 为此,我们使用接收到的post_id_like_unlike的id属性作为参数来获取上面声明的span元素HTML文本( Like / Unlike )。 在这里, type将包含文本Like或Like

function post_like_unlike(post_id_like_unlike,user_session_id)
{
    var type = ($('#'+(post_id_like_unlike.id)).html());
    ..

We also get the post id as the first part after splitting the span id. Remember that we had declared span id in the previous article like this:

拆分范围ID后,我们还将帖子ID作为第一部分。 请记住,我们在上一篇文章中已这样声明了span id:

$post_like_unlike_id=$post_id.'_like_unlike';

The reason for declaring elements like this must be clear to you now. This allows us to use the post id in the JS as we are doing now:

现在必须清楚声明此类元素的原因。 这使我们可以像现在这样在JS中使用帖子ID:

var post_id_of_like_unlike= ((post_id_like_unlike.id).split("_")) [0];
var post_id_like_count = post_id_of_like_unlike+'_like_count';

If the user has clicked on Like we send an AJAX call to post_like.php. Else, we call post_unlike.php. In the callback function, we change the text of Like/Unlike option to Unlike if the user has clicked on Like and vice versa. Also, we increase/decrease the likes count using post_id_like_count.

如果用户单击了Like,我们将AJAX调用发送到post_like.php 。 否则,我们称为post_unlike.php 。 在回调函数中,如果用户单击“ 喜欢” ,则将“ 喜欢/不喜欢”选项的文本更改为“ 不同 ”,反之亦然。 另外,我们使用post_id_like_count增加/减少点赞次数

if (type == 'Like')
{
   $.post('php_scripts/post_like.php',{
        post_id:post_id_of_like_unlike,
        user_id:user_session_id},function(output){
            $('#'+(post_id_like_unlike.id)).html('Unlike');
            $('#'+(post_id_like_count)).html(parseInt($('#'+(post_id_like_count)).html())+1);
       });
}
else 
{
    $.post('php_scripts/post_unlike.php',{
        post_id:post_id_of_like_unlike,
        user_id:user_session_id},function(output){
            $('#'+(post_id_like_unlike.id)).html('Like');
            $('#'+(post_id_like_count)).html(parseInt($('#'+(post_id_like_count)).html())-1);
        });
};

In post_like.php, we update the post document by incrementing total_likes by 1 and pushing the current user id in the array likes_user_ids.

post_like.php ,我们通过增加更新后的文件total_likes 1,推动当前用户ID在阵列likes_user_ids

$collection->update(array('_id' =>$post_id),
                    array('$push' => array('likes_user_ids'=>$user_id),
                          '$inc' => array('total_likes' => 1 )) 
                    );

Similarly, in post_unlike.php, we update the post document by decrementing total_likes by 1 and pulling the user id from the array likes_user_ids.

类似地,在post_unlike.php ,我们通过将total_likes减1并从likes_user_ids数组中likes_user_ids用户ID来更新post文档。

$collection->update(array('_id' => $post_id),
                    array('$pull' => array('likes_user_ids'=>$user_id),
                          '$inc' => array('total_likes' => -1 )) 
                    );

插入评论: (Inserting Comments:)

After understanding how the post insertion and like/unlike functionalities work, you will be able to easily understand how the commenting functionality works. After passing the comment text and post id from index.php to JS and then to new_comment.php, we will update the post document to insert the new comment and increment the count.

了解了帖子插入和喜欢/不喜欢的功能的工作原理之后,您将能够轻松了解注释功能的工作方式。 在将注释文本和发布ID从index.php传递到JS,然后传递给new_comment.php ,我们将更新发布文档以插入新评论并增加计数。

$collection->update(array('_id' => $post_id),
                    array('$push' => array('comments'=> array (
                                                'comment_id'=>$comment_id,
                                                'comment_user_id' =>$user_id,
                                                'comment_text' => $comment_text
                                               )),      
                           '$inc' => array('total_comments' => 1 ))
                    );

We will then append this new comment to the existing list of comments on the post.

然后,我们会将这个新评论添加到帖子的现有评论列表中。

Finally, we have implemented everything we've set out to implement. Fig 1 shows what our final working application looks like. (Note that in the figure, you can see three users. For the purpose of this demonstration, I have changed these users from the session_variables.php file.)

最后,我们已经实现了我们打算实现的所有内容。 图1显示了我们最终的工作应用程序的外观。 (请注意,在该图中,您可以看到三个用户。出于演示的目的,我从session_variables.php文件中更改了这些用户。)

alt

结论: (Conclusion:)

In the two articles of this series, we learned how to design the database schema, understood the HTML structure, and then implemented the whole post mechanism. However, note that the article only shows one way of achieving these features, which may not be the same approach such social networks use. Also, there are lots of other features and issues (security, design, etc.) to be considered in such applications that we may not have discussed here.

在本系列的两篇文章中,我们学习了如何设计数据库架构,理解HTML结构,然后实现了整个发布机制。 但是,请注意,本文仅显示了实现这些功能的一种方法,可能与此类社交网络使用的方法不同。 此外,在此类应用程序中还有许多其他功能和问题(安全性,设计等)需要考虑,我们可能在这里没有进行讨论。

Furthermore, the code does not follow best practices – this is something for the reader to experiment with. Implement object oriented code, use a JavaScript framework, use a PHP framework for the entire back end – the sky is the limit. This post mechanism is merely a hint of how you can implement a single feature in your own social network.

此外,该代码未遵循最佳实践-这是供读者尝试的东西。 实施面向对象的代码,使用JavaScript框架,在整个后端使用PHP框架-无限。 此发布机制只是如何在自己的社交网络中实现单个功能的提示。

To conclude, this article is just a foundation of many things you can achieve using similar concepts. You can go ahead and implement a lot of features which I could not explain here like displaying names of users who liked the post, showing collapsible comments, deleting comments, deleting posts, liking/unliking comments, popular posts, building a more interactive post stream showing posts from user’s friends and other advanced features. If you have any suggestions or critiques, please leave them in the comments below.

总而言之,本文只是使用相似概念可以实现的许多事情的基础。 您可以继续执行许多我无法在此处解释的功能,例如显示喜欢该帖子的用户的姓名,显示可折叠的评论,删除评论,删除帖子,喜欢/不喜欢评论,受欢迎的帖子,构建更具交互性的帖子流显示来自用户朋友的帖子和其他高级功能。 如果您有任何建议或批评,请留在下面的评论中。

翻译自: https://www.sitepoint.com/social-network-style-posting-php-mongodb-jquery-part-2/

mongodb 社交网站

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值