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

news/2024/5/12 20:23:31/文章来源:https://blog.csdn.net/culh2177/article/details/108385237

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 社交网站

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_786671.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

wordpress插件_如何使用Weglot插件翻译WordPress网站

wordpress插件This article on how to translate WordPress websites was originally published by Torque Magazine, and is reproduced here with permission. 这篇有关如何翻译WordPress网站的文章最初由Torque Magazine出版&#xff0c;经许可转载于此。 Translating your…

替换轻松访问内容_轻松检查网站可访问性

替换轻松访问内容A few weeks ago I published an article highlighting popular tools and other considerations to check your site’s accessibility. There I briefly touched on the possible errors these tools look for in your code and how to avoid them. In this …

seo友好html标签_SEO友好的无限滚动

seo友好html标签As a developer, at some point you may have to decide between the old fashioned pagination and the trendy new infinite scroll, using the latest technologies, inspired by internet giants like Facebook and Pinterest. It depends on your requirem…

word mover_使用Mover.io轻松进行网站备份

word moverThe traditional way of doing a website backup is to download and save a local copy of the site files to your computer or to cloud storage services like Dropbox and Amazon S3. 网站备份的传统方式是将站点文件的本地副本下载并保存到您的计算机或Dropbox…

手机网页合适尺寸_网站没有最佳尺寸

手机网页合适尺寸With responsive practically becoming the standard, it’s harder than ever to define the best size for a website. Before responsive became mainstream, we used to base our design width on which screen sizes were popular at the moment. 随着响…

非常nice的网站集合,你还在等什么?

好用的软件千里挑一&#xff0c;实用的网站都在这里。如果不想在电脑上安装些不常用的软件&#xff0c;那就看看这篇文章中分享的网站&#xff0c;有没有你需要的吧&#xff01;壁纸网站--海量好看的壁纸任你挑选http://wallpaperswide.com视频网站--在这里可以看到你想看的视频…

wordpress最佳架构_5个技术难题的最佳WordPress网站建设者

wordpress最佳架构This article is part of a series created in partnership with SiteGround. Thank you for supporting the partners who make SitePoint possible. 本文是与SiteGround合作创建的系列文章的一部分。 感谢您支持使SitePoint成为可能的合作伙伴。 As an ent…

wordpress 占有率_降低WordPress网站跳出率的10条提示

wordpress 占有率A ‘Bounce Rate‘ is simply the percentage of users who visit your site and then navigate away after viewing just a single page. “ 跳出率 ”只是访问您网站并在仅浏览单个页面后便离开网站的用户所占的百分比。 You can make use of Google Analyt…

测试网站性能的工具

If you already consider website design, development, content, and SEO as the parameters of success on the web, then it’s the right time to start giving attention to your website’s loading time. 如果您已经将网站的设计&#xff0c;开发&#xff0c;内容和SEO视…

xx项目重大问题的感受_有关您的下一个网站项目的10个重要问题

xx项目重大问题的感受Web design and development is a long, iterative process. It can span a few weeks or a few months. And as you get immersed in the details, it is quite easy to lose track. Have you met the original goals of the website? Or did you get so…

客户端访问网站的整个流程图_如何阻止整个国家访问您的网站

客户端访问网站的整个流程图Trending posts on SitePoint today: 今天在SitePoint上的热门帖子&#xff1a; What is HTTP/2? 什么是HTTP / 2&#xff1f; Tame Unruly Style Sheets With These Three CSS Methodologies 使用这三种CSS方法来驯服不规则的样式表 Your Regular…

SQL Server 2005全文检索技术在网站上的应用实录

SQL Server 2005全文检索技术在网站上的应用实录 一、前言“人类失去搜索&#xff0c;世界将会怎样?”&#xff0c;同样&#xff0c;很难想象一个拥有极大信息量的行业网站门户没有站内全文搜索将会出现怎样的局面&#xff0c;网站全文检索对于挖掘网站信息和整合网站资源的价…

【网站架构13/100】一步步带你,如何网站架构

2019独角兽企业重金招聘Python工程师标准>>> 何为大型网站 大型网站特性 既然说的是大型网站架构&#xff0c;那么架构的背后自然是解决人因面对大型网站特性而带来的问题。这样可以先给大家说下大型网站的特性&#xff0c;这些特性带来的问题就是人要解决的问题&am…

1小时内即可成为WordPress杀手级会员网站

No matter what type of business you’re in, creating a membership is a lucrative method of increasing your income. You can create recurring revenue, get ongoing support from your audience, and expand your brand’s reach. You can use memberships to sell onl…

wordpress攻击思路_防止针对WordPress网站的暴力攻击

wordpress攻击思路A ‘brute force’ login attack is a type of attack against a website to gain access to the site by guessing the username and password, over and over again. Other kinds of hacks rely on website vulnerabilities whereas a brute force attack i…

wordpress用cdn_使用CDN加快您的WordPress网站

wordpress用cdnHave you ever imagined speeding your WordPress website by implementing a Content Delivery Network (CDN)? This tutorial illustrates how the CDN configuration using Amazon CloudFront and Rackspace Cloud Files (with Akamai CDN) speeds up the W…

wordpress插件_3个最佳WordPress插件,使您的网站移动友好

wordpress插件The mobile web is growing exponentially. If your website doesn’t support mobile phones and tablets now, you can guarantee it’ll become increasingly important over the coming years. 移动网络正呈指数级增长。 如果您的网站现在不支持手机和平板电脑…

wordpress 大网站_加快您的WordPress网站

wordpress 大网站This article was sponsored by GoDaddy. Thank you for supporting the companies who make SitePoint possible! 本文由GoDaddy赞助。 感谢您对使SitePoint成为可能的公司的支持&#xff01; As one of the top user experience factors, website performan…

Simbla:网站建设者的另一种方法

This article was sponsored by Simbla. Thank you for supporting the sponsors who make SitePoint possible. 本文由Simbla赞助。 感谢您支持使SitePoint成为可能的赞助商。 I have tried and used many different types of website builders over the past few years. I’…

JSP网站开发基础总结《九》(转)

Spring Boot 配置过滤器Filter及控制多个Filter的执行顺序 1、实现javax.servlet包下的Filter接口 2、Component和Order&#xff08;可选&#xff0c;有多个过滤器时可添加&#xff09;注解&#xff0c;Order用于控制过滤器的级别&#xff0c;值越小级别越高 3、过滤的业务逻辑…