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

news/2024/5/12 1:39:01/文章来源:https://blog.csdn.net/culh2177/article/details/108385244

mongodb 社交网站

Post mechanisms similar to Facebook are nowadays very common within any application. The concept of Post-Like-Comment is familiar to everyone who ever used a social network. In this article, we will learn how to create a similar working model wherein the user will be able to post his status, like posts and comment on them. What’s more interesting is that after learning things from this article, going forward you will be able to implement a lot of other features on your own.

如今,类似于Facebook的发布机制在任何应用程序中都非常普遍。 喜欢评论的概念对于曾经使用社交网络的每个人都很熟悉。 在本文中,我们将学习如何创建一个类似的工作模型,在该模型中,用户将能够发布其状态,例如帖子并对其发表评论。 更有趣的是,从本文中学到东西之后,您将能够自己实现许多其他功能。

I’ll be using PHP as the coding language, MongoDB as the database and jQuery for JavaScript operations. It is assumed the reader is familiar with the basics of PHP and MongoDB to understand the article thoroughly. However, note that the article is written in a very generic and newbie-friendly manner and there is a lot to learn from it. So, even if you are not using Mongo DB or jQuery, you can easily adapt to or replace those technologies with those you prefer.

我将使用PHP作为编码语言,使用MongoDB作为数据库,并使用jQuery进行JavaScript操作。 假定读者熟悉PHP和MongoDB的基础知识以全面理解本文。 但是,请注意,本文是以非常通用且对新手友好的方式编写的,可以从中学到很多东西。 因此,即使您不使用Mongo DB或jQuery,也可以轻松地将其适应或替换为您喜欢的技术。

There are two articles in this series. In the first article, we will learn the database architecture, design the stream and think up the application flow structure that we are going to adapt. In the next article of this series, we will write the code which will eventually allow us to create a new post, like/unlike a post and comment on it. Understand that the first article is more of a base for the functionalities we are going to implement in the next part. As such, there will be cases where you will not understand the actual implementation logic of certain things until you find out more in the second article. The articles are accompanied by downloadable code for your reference. Please note that this code is written in procedural form and as such definitely not a best practice. This simplified form was chosen to make the implementation itself more newbie-friendly, and this post mechanism will be re-implemented in an object oriented manner in a more complex article down the line.

本系列中有两篇文章。 在第一篇文章中,我们将学习数据库体系结构,设计流并思考我们将要适应的应用程序流结构。 在本系列的下一篇文章中,我们将编写代码,该代码最终将使我们能够创建一个新帖子,就像/不喜欢帖子并对其进行评论。 理解第一篇文章更多地是我们将在下一部分中实现的功能的基础。 因此,在某些情况下,您将不了解某些事物的实际实现逻辑,除非您在第二篇文章中找到更多信息。 这些文章随附可下载的代码,以供您参考。 请注意,此代码是以程序形式编写的,因此绝对不是最佳实践。 选择这种简化形式是为了使实现本身对新手更友好,并且将在更复杂的文章中以一种面向对象的方式重新实现此发布机制。

Before getting started, let us look at the final work we will develop (Fig 1 ).

在开始之前,让我们看一下我们将要开发的最终工作( 图1 )。

alt

下载代码: (Download Code:)

Download the code provided with the article from its Github repo. You will find the following files in it:

从其Github存储库下载本文随附的代码。 您将在其中找到以下文件:

index.php : This is the main file which displays all the posts and from where the user will interact.

index.php :这是显示所有帖子以及用户与之互动的主文件。

mongo_connection.php : This file contains the common MongoDB connection code. If you have made any changes to the MongoDB connection credentials, you should specify them here. In all other PHP files, we will include this file to use the common MongoDB connection code. Make sure MongoDB is installed by following the installation instructions and installing the PHP drivers.

mongo_connection.php :此文件包含常见的MongoDB连接代码。 如果您对MongoDB连接凭据进行了任何更改,则应在此处指定它们。 在所有其他PHP文件中,我们将包括此文件以使用通用的MongoDB连接代码。 按照安装说明并安装PHP驱动程序,确保已安装MongoDB。

session_variables.php : The article expects that we have some common fields such as user id, user name and user’s profile picture stored in session variables as they are very frequently used throughout the application. Generally such information is set when the user logs in but for the purpose of the article, we will set it in this file.

session_variables.php :本文希望我们在会话变量中存储一些常用字段,例如用户ID,用户名和用户个人资料图片,因为它们在整个应用程序中都很常用。 通常,此类信息是在用户登录时设置的,但出于本文的目的,我们将在此文件中进行设置。

script.js and style.css contains all the Javascript and CSS code. jquery.js is the standard jQuery library file.

script.jsstyle.css包含所有Javascript和CSS代码。 jquery.js是标准的jQuery库文件。

php_scripts : This folder contains all the PHP files that we will call through AJAX to do PHP operations for inserting the post, performing like/unlike on the post and inserting comments.

php_scripts :此文件夹包含我们将通过AJAX调用的所有PHP文件,以执行PHP操作,以插入帖子,对帖子执行类似/不相似以及插入评论。

images : This folder contains profile pictures of all the users.

images :此文件夹包含所有用户的个人资料照片。

数据库结构: (Database Structure:)

The users collection will be a simple one containing user id, user name and profile picture of the user as shown below:

用户集合将是一个简单的集合,其中包含用户ID,用户名和用户的个人资料图片,如下所示:

{
"_id": ObjectId("5222f8e0d85242c01100000d"),
"name": "Richard Garry",
"profile_pic": "profile_pic_3.jpg" 
}

Another collection posts_collection will maintain all the information related to posts as shown in the sample entry below:

另一个集合posts_collection将维护与帖子相关的所有信息,如下面的示例条目所示:

{
"_id": ObjectId("5222f885d85242c011000009"),
"post_author_id": ObjectId("5146bb52d8524270060001f4"),
"post_text": "Let's get started !!!\t\t\t",
"timestamp": "Sun, 01-Sep-2013",
"total_comments": NumberInt(3),
"total_likes": NumberInt(2) ,
"likes_user_ids": {
"0": ObjectId("52147f70d85242cc12000010"),
"1": ObjectId("5222f8e0d85242c01100000d") 
},
"comments": {
"0": {
"comment_id": ObjectId("5222f897d85242c01100000a"),
"comment_user_id": ObjectId("52147f70d85242cc12000010"),
"comment_text": "This is comment 1 !!" 
},
"1": {
"comment_id": ObjectId("5222f8a7d85242c01100000b"),
"comment_user_id": ObjectId("5222f8e0d85242c01100000d"),
"comment_text": "This is comment 2 !!" 
} 
}
}

Most of the fields in the document are self-explanatory. likes_user_ids contains user ids of all the users who have liked the post. comments is an array which contains sub-documents to store the comments information.

该文档中的大多数字段都是不言自明的。 likes_user_ids包含所有喜欢该帖子的用户的用户ID。 评论是一个数组,其中包含用于存储评论信息的子文档。

了解流设计: (Understanding Stream Design:)

Let us first place a text area where the user will enter the post text and a button Create New Post (as shown in Fig 2 ) using the following code:

让我们首先使用以下代码将一个文本区域放置到用户将在其中输入帖子文本和一个按钮Create New Post( 如图2所示)的地方:

alt
<div id="div_post_content">
<textarea id="post_textarea">
</textarea>
</div>
<div class="div_post_submit">
<input type="button" value="Create New Post" id="btn_new_post" class="button_style"/>
</div>

Our index page displays all the posts in a stream-like view. Looking at the code in index.php, we will explain how this data is fetched and displayed one step at a time:

我们的索引页面以类似流的视图显示所有帖子。 查看index.php中的代码,我们将解释如何一次获取和显示此数据:

We first fetch all the posts from the database and sort them with descending _id so as to get the last inserted posts first.

我们首先从数据库中获取所有帖子,并以_id降序对其进行排序,以便首先获取最后插入的帖子。

$posts_cursor=$collection->find()->sort(array('_id'=>-1));

Now, we iterate over all the fetched posts using foreach and get the post id, post text and user id of post author:

现在,我们使用foreach遍历所有提取的帖子,并获取帖子作者的帖子ID,帖子文本和用户ID:

foreach($posts_cursor as $post)
{
$post_id=$post['_id'];
$post_text=$post['post_text'];
$post_author_id=$post['post_author_id'];
…

Using the user id, we can now get the user name and profile picture link from the users collection.

现在,使用用户ID,我们可以从用户集合中获取用户名和个人资料图片链接。

$collection = $database->selectCollection('users');
$post_author_details = $collection->findOne(array('_id' =>$post_author_id));
$post_author = $post_author_details['name'];
$post_author_profile_pic = $post_author_details['profile_pic'];

Understand that on our page, we will have many posts displayed together. Each post will have its Like button, like count, comments and comments count. We need to uniquely identify each of these things for each individual post so that when the user does any operation on any post (liking, commenting), we know which post to update. For this, we will initialize some variables which we will use as id of corresponding HTML elements later:

要了解的是,在我们的页面上,我们将同时显示许多帖子。 每个帖子都会有其“ 赞”按钮,例如计数,评论和评论计数。 我们需要为每个单独的帖子唯一地标识所有这些内容,以便当用户对任何帖子进行任何操作(点赞,评论)时,我们都知道要更新哪个帖子。 为此,我们将初始化一些变量,稍后将其用作相应HTML元素的ID

$post_like_unlike_id=$post_id.'_like_unlike';
$post_like_count_id=$post_id.'_like_count';
$post_comment_count_id = $post_id.'_comment_count';
$post_self_comment_id=$post_id.'_self_comment';
$post_comment_text_box_id=$post_id.'_comment_text_box';

We now check whether the current user has already liked the post or not. For this, we check if the user id of the current user is present in likes_user_ids array fetched from database. If the user has already liked the post, we set $like_or_unlike variable to display Unlike. But if the user has still not liked the post, we need to display Like option. We will use $like_or_unlike later in our HTML to display Like or Unlike option.

现在,我们检查当前用户是否已经喜欢该帖子。 为此,我们检查从数据库中获取的likes_user_ids数组中是否存在当前用户的用户ID。 如果用户已经很喜欢这个岗位,我们设置$ like_or_unlike变量来显示不同 。 但是,如果用户仍然不喜欢该帖子,则需要显示“ 赞”选项。 我们将在以后HTML使用$ like_or_unlike显示相同的或不同的选择。

if(in_array($_SESSION['user_id'],$post['likes_user_ids']))
{
$like_or_unlike='Unlike';
}
else
{
$like_or_unlike='Like';
}
// you can also write this in short ternary form:
$like_or_unlike = (in_array($_SESSION['user_id'],$post['likes_user_ids'])) ? 'Unlike' : 'Like';

We will now use the variables initialized above and create the HTML structure to display the post. Each post_wrap div will display one post and the id of this post_wrap will be the post id drawn from the database.

现在,我们将使用上面初始化的变量并创建HTML结构来显示帖子。 每个post_wrap div将显示一个帖子,并且该post_wrapid将是从数据库中提取的ID。

<div class="post_wrap" id="<?php echo $post['_id'];?>">
<div class="post_wrap_author_profile_picture">
<img src="images/<?php echo $post_author_profile_pic;?>" />
</div>  
<div class="post_details">  
<div class="post_author">
<?php echo $post_author ?> 
</div>
<div class="post_text">
<?php echo $post_text; ?>
</div>
</div>

Now let's show the number of likes and comments. Note that we had initialized some variables in the previous steps. Those variables are going to be used here. $like_or_unlike displays the Like or Unlike text set earlier while $post_like_count_id and $post_comment_count_id are used to give ids of spans displaying the likes and comments count.

现在,让我们显示喜欢和评论的数量。 请注意,在前面的步骤中我们已经初始化了一些变量。 这些变量将在这里使用。 $like_or_unlike显示相同的或不同的文字集,而更早$post_like_count_id$post_comment_count_id是用来给IDS显示喜好和评论数跨度。

You will understand the use of assigning these ids in the next article, where we will have to get data and update it for each individual post.

在下一篇文章中,您将了解分配这些ID的用法,在该文章中,我们将必须获取数据并针对每个帖子进行更新。

<div class="comments_wrap">
<span>
<span><img src="images/like.png" /></span>     
<span class="post_feedback_like_unlike" id="<?php echo $post_like_unlike_id;?>"><?php                  echo $like_or_unlike; ?></span>                    
<span class="post_feedback_count" id="<?php echo $post_like_count_id; ?>"><?php echo                    $post_like_count;?></span>
</span>
<span>
<span class="post_feedback_comment"> <img src="images/comment.png" /> Comment</span>               <span class="post_feedback_count" id="<?php echo $post_comment_count_id; ?>"><?php echo                     $post_comment_count;?></span>
</span>
</div>

The above code would result in something like this (Fig 3):

上面的代码将导致如下所示(图3):

alt

Now, to show the comments related to each post, we iterate over the comments array retrieved from database and initialize variables to be used in HTML. For each comment, we perform a find query on the users collection to fetch the comment author’s name and profile picture link.

现在,为了显示与每个帖子相关的评论,我们遍历从数据库检索的comment数组,并初始化要在HTML中使用的变量。 对于每个评论,我们在users集合上执行查找查询,以获取评论作者的姓名和个人资料图片链接。

for($i=0;$i<$post_comment_count;$i++)
{                                           
$comment_id=$post['comments'][$i]['comment_id'];                           
$comment_text=$post['comments'][$i]['comment_text'];                   
$comment_author_id=$post['comments'][$i]['comment_user_id'];
$collection = $database->selectCollection('users');
$comment_author_details = $collection->findOne(
array('_id' => new MongoId($comment_author_id))
);                             
$comment_author = $comment_author_details['name'];
$comment_author_profile_pic = $comment_author_details['profile_pic'];

Following is the HTML code to display a single comment using the variables initialized above: (Output: Fig 4)

以下是使用上面初始化的变量显示单个注释HTML代码:(输出: 图4 )

<div class="comment" id="<?php echo $comment_id; ?>">                 
<div class="comment_author_profile_picture">
<img src="images/<?php echo $comment_author_profile_pic; ?>"/>
</div>
<div class="comment_details">
<div class="comment_author" >
<?php echo $comment_author; ?>
</div>
<div class="comment_text" >
<?php echo $comment_text; ?>
</div>
</div>
</div>
alt

After displaying all the comments fetched form the database, we want to show a blank comment box wherein the current user can comment.

在显示从数据库中获取的所有评论之后,我们想要显示一个空白评论框,当前用户可以在其中进行评论。

<div class="comment" id="<?php echo $post_self_comment_id; ?>">
<div class="comment_author_profile_picture">
<img src="images/<?php echo $_SESSION['user_profile_pic']; ?>" />
</div>
<div class="comment_text">
<textarea placeholder="Write a comment..." id="<?php echo $post_comment_text_box_id;?>" >
</textarea>
</div>
</div>
alt

应用流程结构: (Application Flow Structure:)

alt

Let us now understand how the application flow will work by taking an example of inserting a new post. Don’t worry about the coding part for now as we are going to see that in the next article.

现在让我们以插入新帖子为例,了解应用程序流程将如何工作。 现在不用担心编码部分,我们将在下一篇文章中看到。

  • The first PHP file (index.php) is the main page from where the user will enter the post text and click on Create New Post button. For simplicity's sake, we'll put a JavaScript function new_post as the click handler of this button and pass the post_text and user_id as its parameters.

    第一个PHP文件( index.php )是主页,用户从中输入帖子文本,然后单击“ 创建新帖子”按钮。 为简单起见,我们将JavaScript函数new_post用作此按钮的单击处理程序,并将post_textuser_id传递为其参数。

  • The JavaScript function will receive these parameters and send an AJAX POST request to a PHP file (insert_new_post.php) passing forward the same parameters it received.

    JavaScript函数将接收这些参数,并将AJAX POST请求发送到PHP文件( insert_new_post.php ),并转发与接收到的相同的参数。

  • This PHP file does the work of inserting the received post text into the database. After doing the database operation, it prepares HTML content containing the new post which will be sent as output of the JavaScript function. This output will later be rendered on the main page. In reality, the PHP function should return JSON to reduce bandwidth, and the view file should just include the data into a prepared template, but seeing as our app is just a demonstration, this will do.

    该PHP文件完成了将收到的帖子文本插入数据库的工作。 完成数据库操作后,它将准备包含新文章HTML内容,这些内容将作为JavaScript函数的输出发送。 稍后将在主页上呈现此输出。 实际上,PHP函数应返回JSON以减少带宽,并且视图文件应仅将数据包含在准备好的模板中,但是看到我们的应用只是一个演示,就可以了。

  • The JavaScript function receives the output sent by the PHP file and inserts it into the main page HTML.

    JavaScript函数接收PHP文件发送的输出,并将其插入到主页HTML中。

The flow for all other operations (like commenting, liking/unliking post) is going to be similar to what we just saw for the example of inserting a post.

所有其他操作(例如,评论,喜欢/不喜欢帖子)的流程将类似于我们在插入帖子的示例中看到的流程。

结论: (Conclusion:)

In this article, we explained the database architecture, post stream design and application flow. In the next part of this series, we are going to use these structures and develop our functionality of inserting posts, like/unlike and commenting.

在本文中,我们解释了数据库体系结构,后流设计和应用程序流程。 在本系列的下一部分中,我们将使用这些结构并开发我们插入帖子(如/不喜欢和发表评论)的功能。

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

mongodb 社交网站

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

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

相关文章

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 peoples statuse…

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’…