Home  >  Article  >  Backend Development  >  Code analysis of a simple QQ group chat case (PHP implementation)

Code analysis of a simple QQ group chat case (PHP implementation)

易达
易达Original
2020-06-01 12:48:283559browse

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

Code analysis of a simple QQ group chat case (PHP implementation)

Create table qq_group table member group

Code analysis of a simple QQ group chat case (PHP implementation)

Create table qq_msg message table

Code analysis of a simple QQ group chat case (PHP implementation)

Create table qq_user member table

Code analysis of a simple QQ group chat case (PHP implementation)

Create table qq_user_group_relation member and group relationship table

Code analysis of a simple QQ group chat case (PHP implementation)

Create table qq_user_login_record member login information record table

Code analysis of a simple QQ group chat case (PHP implementation)

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

1Code analysis of a simple QQ group chat case (PHP implementation)

2. There are 2 administrative department groups, friend group (qq_group)

2Code analysis of a simple QQ group chat case (PHP implementation)

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)

3Code analysis of a simple QQ group chat case (PHP implementation)

In order to have messages in the administrative group, we first try to add a record in the message table

4Code analysis of a simple QQ group chat case (PHP implementation)

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"=>&#39;mysql&#39;,
           "hostname"=>"127.0.0.1",
           "database"=>"qq",
           "username"=>"root",
           "password"=>"root"
       );
       $this->link = mysqli_connect($config[&#39;hostname&#39;],$config[&#39;username&#39;],
        $config[&#39;password&#39;],$config[&#39;database&#39;]);
       
    }
}
?>

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=&#39;&#39;){
        //创建连接
        $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 (&#39;{$content}&#39;,".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(&#39;Y-m-d H:i:s&#39;,$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,&#39;&#39;,$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[&#39;login_time&#39;]);

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

222Code analysis of a simple QQ group chat case (PHP implementation)

Message table data has been added

111Code analysis of a simple QQ group chat case (PHP implementation)

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn