


Code analysis of a simple QQ group chat case (PHP implementation)
Question:
Use object-oriented programming to implement the following business logic:
1. Zhang San logged in to qq using account a and password b
2. Display Get the last login time of Zhang San
3. Zhang San checked the information of the administrative department group within 1 hour (there are Zhang San, Li Si and Wang Wu in this group, of which Zhang San is the group leader)
4. Output Zhang San's information
5. Suddenly Zhang San received a friend Li Si's information: Information called: Zhang San, I am Li Si, what are you doing? (Zhang San created a friend group with friend Li Si in it)
6. Zhang San replied to Li Si: I’m thinking of you
First let’s analyze it
1. Process analysis
1. Zhang San logged into qq using account a and password b
2. Display Zhang San’s last login time
3. Zhang San checked the information of the administrative department group within 1 hour (there are Zhang San, Li Si, and Wang Wu in this group, of which Zhang San is the group leader)
4. Output Zhang These messages seen by San
5. Li Si sent a message to Zhang San. The message was: Zhang San, I am Li Si, what are you doing?
6. Zhang San sent a message to Li Si, the message is: I’m thinking of you
2. Function analysis:
1. Identify the object
QQ members, QQ member login information, QQ member messages, QQ member groups, the relationship between QQ members and groups (one-to-many)
2. Identify the attributes of the object
QQ member:
Attributes: id, name, account number, password
QQ member login information: (A member can log in multiple times and have multiple login records)
Attributes: id, member id, login time
QQ member message: Attributes: id, content, sending time, sender, recipient, status (read, unread), viewing time
QQ member group: Attributes: id, created member, group name, group creation time
The relationship between QQ members and groups: (This relationship is also a class and can also produce many instances)
Attributes: id, user_id, group_id, create_time
3. Method of identifying objects
QQ members:
Method:
1. Log in,
2. View the message
3. Send the message
QQ member login information:
1. Save the member’s login Information
2. Obtain the user’s last login information
QQ member message:
Method: Modify status (can be modified to read), obtain member information, add members Message
QQ member group:
Method: 1. Obtain all groups 2. Create a group (Zhang San checked the administrative department group, indicating that this group must have been created by someone)
The relationship between QQ members and groups:
Method: 1. View all her groups according to the member = Get all the groups of the member
2. According to a group, you can view this group All members in
3. Database analysis:
1.QQ members: The attributes correspond to the fields in the table
2.QQ Member message: The attributes correspond to the fields in the table
3. QQ member group: The attributes correspond to the fields in the table
4. The intermediate table between QQ members and groups: because A member can belong to multiple member groups, so you need to have this table
Fields: id, member id, group id, group joining time
5. QQ member login information list
After the analysis is completed, let’s do the specific operations
1. Create the database and initialize the data
Create the database. Let’s try to make the name as easy to understand as possible. It’s called qq
Create table qq_group table member group
Create table qq_msg message table
Create table qq_user member table
Create table qq_user_group_relation member and group relationship table
Create table qq_user_login_record member login information record table
Initialization data, what is the startup data of the project
1. The members include Zhang San, Li Si, and Wang Wu. They have account passwords
2 respectively. They have 2 groups: administrative department group and friend group
.3. Zhang San created an administrative department group, and Zhang San, Li Si, and Wang Wu are all in this group
4. Zhang San also created a friend group, which includes Li Si
Next we fill in these data into the database
1. The members are Zhang San, Li Si, and Wang Wu. They have account passwords (qq_user) respectively
2. There are 2 administrative department groups, friend group (qq_group)
3. Zhang San created an administrative department group, Zhang San, Li Fourth, both Wang and Wu are in the group
4. Zhang San also created a friend group, which includes Li Si (qq_user_group_relation)
In order to have messages in the administrative group, we first try to add a record in the message table
2. Create Class, implementation class
According to analysis, we should create at least 5 classes, but all classes require database connection, so we can create a database class separately, so 6 classes need to be created
In order to facilitate management, we put these classes in the model directory
model/Mysql.class.php
<?php //数据库连接类 class Mysql{ //属性:id,姓名,账号,密码,登录时间 public $link = "";//id public function __construct(){ //创建连接 $this->init(); } public function __destruct(){ //销毁数据库连接 if( $this->link ){ mysqli_close($this->link); } } //创建连接,初始化连接 public function init( ){ //创建连接 $config = Array( "type"=>'mysql', "hostname"=>"127.0.0.1", "database"=>"qq", "username"=>"root", "password"=>"root" ); $this->link = mysqli_connect($config['hostname'],$config['username'], $config['password'],$config['database']); } } ?>
model/Group.class.php
<?php require_once "MySql.class.php"; class Group{ // 属性:id,创建会员,群名称,群的创建时间 public $id = ""; public $userid = ""; public $groupName = ""; public $createTime = ""; public $mySql = ""; public $tableName = "qq_user_group"; public function __construct(){ $this->mySql = new MySql(); } //1.获取所有的群 //如果不指定具体的创建人,可以获取所有的群 public function getAll($creatorUserId=''){ //创建连接 $conn = $this->Mysql->link; //写sql,执行sql $where = ""; if( !empty($userid) ){ $where .= " creator_user_id=".$creatorUserId; } $sql = "select * from {$this->tableName} where 1=1 and {$where}"; //执行sql $result = mysqli_query($conn,$sql); //获取数据 // $list = mysqli_fetch_all($result); $list = Array(); while( $row=mysqli_fetch_assoc($result) ){ $list[] = $row; } //end //返回数据 return $list; } //2.创建群 留给同学些,课上就不写了,因为目前的最终效果不需要呈现,默认已经是张三创建好了 public function create(){ echo "创建了群"; } } ?>
Message.class.php
<?php require_once dirname(__FILE__)."/MySql.class.php"; // 会员消息类 class Message{ //属性:id,内容,发送时间,发送人,接收人,状态(已读,未读),查看时间 public $id = ""; public $content = ""; public $sendTime = ""; public $sendUserId = ""; public $toUserId = ""; public $status = ""; public $readTime = ""; public $mySql = ""; public $tableName = "qq_msg"; public function __construct(){ $this->mySql = new MySql(); } // 方法:修改状态(可以被修改为已读),查看消息,发送消息 public function updateStatus($id,$status){ //创建连接 $conn = $this->mySql->link; //写sql,执行sql $sql = "update {$this->tableName} set status={$status} where id={$id}"; //执行 $result = mysqli_query($conn,$sql); if( $result ){ return true; }else{ return false; } } //查看会员消息列表 public function getMsgList($userid,$type,$startTime,$endTime,$groupId){ //创建连接 $conn = $this->mySql->link; //写sql,执行sql $where = " to_user_id={$userid} "; if( $type !=""){//这里特别注意不能直接写!empty,会导致0的情况考虑不进来 而0表示未读 $where .= " and status=".$type; } if( !empty($startTime) && !empty($endTime) ){ //判断时间 $where .= " and create_time between {$startTime} and {$endTime}"; } if( $groupId ){ $where .= " and group_id = ".$groupId; } $sql = "select * from {$this->tableName} where {$where}"; //执行 $result = mysqli_query($conn,$sql); //获取数据 // return mysqli_fetch_all($result); $list = Array(); while( $row=mysqli_fetch_assoc($result) ){ $list[] = $row; } return $list; } //添加消息 public function add($userid,$content,$toUserId,$groupId){ //创建连接 $conn = $this->mySql->link; //写sql,执行sql $sql = "insert into {$this->tableName} (content,create_time,send_user_id, to_user_id,status,read_time,group_id) values ('{$content}',".time().",{$userid}, {$toUserId},0,0,".$groupId.") "; //执行 $result = mysqli_query($conn,$sql); if( $result ){ return true; }else{ return false; } } } ?>
model/User.class.php
<?php //引入UserLoginInfo require_once "MySql.class.php"; require_once "UserLoginInfo.class.php"; require_once "Message.class.php"; class User{ //属性:id,姓名,账号,密码,登录时间 public $id = "";//id public $name = "";//姓名 public $username = "";//账号 public $password = "";//密码 public $mySql = ""; public $tableName = "qq_msg"; public function __construct($id,$name,$username,$password){ //初始化对象 $this->id = $id; $this->name = $name; $this->username = $username; $this->password = $password; $this->mySql = new MySql(); } public function login( $inputUsername,$inputPassword ){ //登录逻辑 //判断用户名和密码是否正确 if( $inputUsername != $this->username || $inputPassword !=$this->password){ return array("msg"=>"用户名或者账号错误"); } //登录成功 $logintime = time(); // echo $this->name."使用账号:{$inputUsername}和密码{$inputPassword}登录了, // 登录时间为:".date('Y-m-d H:i:s',$logintime); //将登录信息保存到数据库 $logininfo = new UserLoginInfo(); $result = $logininfo->save($this->id); return $result; } //查看消息 public function getMessage($startTime,$endTime,$groupId){ //查看消息相当于通过查看这个动作和消息进行了互动 //所以通过方法的调用来执行 $messageModel = new Message(); return $messageModel->getMsgList($this->id,'',$startTime,$endTime,$groupId); } //发送消息相当于通过查看这个动作和消息进行了互动 public function sendMessage($content,$toUserId,$groupId){ //所以通过方法的调用来执行 $messageModel = new Message(); return $messageModel->add($this->id,$content,$toUserId,$groupId); } } ?>
model/UserGroupRelation.class.php
<?php require_once "Mysql.class.php"; class UserGroupRelation{ // 属性:id,创建会员,群名称,群的创建时间 public $id = ""; public $userid = ""; public $groupName = ""; public $createTime = ""; public $mySql = ""; public $tableName = "qq_user_group_relation"; public function __construct(){ $this->mySql = new MySql(); } //1.获取一个群里所有的会员 根据群获取会员 public function getUserList($groupid){ //创建连接 $conn = $this->mySql->link; //写sql,执行sql $sql = "select * from {$this->tableName } where group_id={$groupid}"; //执行 $result = mysqli_query($conn,$sql); //获取数据 // return mysqli_fetch_all($result); $list = Array(); while( $row=mysqli_fetch_assoc($result) ){ $list[] = $row; } return $list; } //2.根据某个会员获取他所有的群 public function getGroupList($userid){ //创建连接 $conn = $this->mySql->link; //写sql,执行sql $sql = "select * from {$this->tableName } where user_id={$userid}"; //执行 $result = mysqli_query($conn,$sql); //获取数据 // return mysqli_fetch_all($result); $list = Array(); while( $row=mysqli_fetch_assoc($result) ){ $list[] = $row; } return $list; } } ?>
model/UserLoginInfo.class.php
<?php require_once "Mysql.class.php"; class UserLoginInfo{ //属性:id,会员id,登录时间 public $id = "";//id public $userid = "";//姓名 public $loginTime = "";//登录时间 public $mySql = ""; public $tableName = "qq_user_login_record"; public function __construct(){ $this->mySql = new MySql(); } //方法: public function save( $userid ){ //添加用户登录记录 $logintime = time(); //保存到数据库 //创建连接 $conn = $this->mySql->link; //写sql执行sql $sql = "insert into ".$this->tableName. "(user_id,login_time) values({$userid}, {$logintime} )"; //执行 $result = mysqli_query($conn,$sql); //这种增,删,改的动作返回的结果是一个数字 1表示成功 if( $result ){ return true; }else{ return false; } } //获取用户最后登录信息 public function getLastLoginInfo($userid){ //创建连接 $conn = $this->mySql->link; //写sql执行sql $sql = "select * from ".$this->tableName. " where user_id={$userid} order by id desc limit 2"; //执行 $result = mysqli_query($conn,$sql); //获取数据 $lastLoginInfo = mysqli_fetch_assoc($result); return $lastLoginInfo; } } ?>
3. Writing process
Create index.php
<?php //业务代码 require_once "model/Message.class.php"; require_once "model/User.class.php"; require_once "model/UserGroupRelation.class.php"; require_once "model/UserLoginInfo.class.php"; //张三登录 $zhangsan = new User(1,"张三","a","b"); // //登录 $zhangsan->login("a","b"); echo $zhangsan->name."使用账号a和密码b 登录了<br/><br/>"; //输出最后登录时间 $logininfoModel = new UserLoginInfo(); //获取最后登录信息 $lastLoginInfo = $logininfoModel->getLastLoginInfo($zhangsan->id); $lastLoginTime = date("Y-m-d H:i:s",$lastLoginInfo['login_time']); echo $zhangsan->name."最后登录时间为".$lastLoginTime."<br/><br/>"; // 2.张三查看了 1个小时内的行政部门群的信息(这个群里有张三,李四,王五,其中张三是群主) $startTime= strtotime("-1 hour"); $endTime = time(); $msglist = $zhangsan->getMessage($startTime,$endTime,1);//查看行为 echo "张三查看了 1小时内的行政部门群的信息<br/><br/>"; echo "<b>张三看到的信息是</b></br/><br/>"; //3.输出张三看到的这些信息 // print_r($msglist); foreach( $msglist as $msg ){ echo "【发送人id】:".$msg["send_user_id"]."【内容】:".$msg["content"]."<br/>"; } echo "<br/><br/>"; //4.突然张三收到好友李四的信息:信息叫:张三,你在干嘛 //相当于是李四给张三发送了消息 $lisi = new User(2,"李四","lisi","123456"); $lisi->sendMessage("张三,我是李四,你在干嘛",$zhangsan->id,2); echo "李四发了信息给张三,说“张三,我是李四,你在干嘛”<br/><br/>"; //5.张三回复李四:我在想你呀 $zhangsan->sendMessage("我在想你呀",$lisi->id,2); echo "张三回复了李四,说“我在想你呀”"; ?>
The running results are as follows:
Zhang San logged in using account a and password b
Zhang San’s last login time was 2020-06-01 12:40:20
Zhang San checked the information of the administrative department group within 1 hour
The information Zhang San saw was
[Sender ID]:3[Content]: Zhang San, I am Wang Wu
Li Si sent a message to Zhang San, saying "Zhang San, I am Li Si, what are you doing?"
Zhang San replied to Li Si, saying " I'm thinking of you."
Let's take a look at the changes in the tables in the database
The login information table data has increased
Message table data has been added
Summary:
1. Explained a simple QQ member login chat scenario
The above is the detailed content of Code analysis of a simple QQ group chat case (PHP implementation). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.
