【PHP小项目使用MVC架构】

时间:2024-01-07 21:12:44

小项目名称是雇员管理系统。

mvc是一种项目的开发模式,中文名称为模式视图控制器,是强制程序员将数据的输入、处理、输出分开的一种开发模式。

在这个小项目中,控制器使用service作为后缀名。

项目uml图解概述:

【PHP小项目使用MVC架构】

在此之前,需要先创建数据库empmanage,同时创建两张表,一张表为admin,令一张表为emp,创建admin表的sql语句:

create table admin
(
id int primary key,
name varchar(32) not null,
password varchar(64) not null
); create table emp(
id int primary key auto_increment,
name varchar(64) not null,
grade tinyint /****1表示1级工人,2表示2级工人*****/,
email varchar(64) not null,
salary float
);

按照字段名向admin表插入1条管理员用户数据,向emp表插入几万条数据即可,向emp表插入数据的时候使用mysql的蠕虫复制功能,分分钟就可以搞定。

将root密码改为5a6f38,否则连接不到数据库。

下面将会将文件名以及文件中的源代码介绍给大家。

login.php

 <?php
require_once 'common.php';
?>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
</head>
<!--此版本完成了验证码验证的问题--> <body>
<h1>管理员登陆界面</h1>
<form action="loginProcess.php" method="post">
<table>
<tr>
<td>请输入用户id:</td>
<td><input type="text" name="admin_id" value="<?php echo getUserName();?>"/></td>
</tr> <tr>
<td>请输入用户密码:</td>
<td><input type="password" name="admin_password" value="<?php echo getPassword();?>"/></td>
</tr> <tr>
<td>请输入验证码:</td>
<td><input type="text" name="checkCode"/></td>
<td><img src="checkCode.php" onclick="this.src='checkCode.php?re='+Math.random()"/></td>
</tr>
<tr>
<td colspan="2">
两周内免登陆本系统:
<input type="checkbox" name="userinf" value="on" checked="checked"/>
</td>
</tr> <tr>
<td><input type="submit" value="单击登陆"/></td>
<td><input type="reset" value="重新填写"/></td>
</tr>
</table>
</form> <?php
$error="初始值";
$error=$_GET['error'];//使用header传递参数,默认的提交方式是GET
echo "<font color=red>".$error."</font>";
?>
</body>
</html>

addEmp.php

 <?php
/**
* 进行用户验证
*/
require_once 'common.php';
checkUser();
?> <html>
<!--这个是专门针对添加用户设计的界面-->
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
</head>
<body>
<center><h1><font size='30px'>这里是添加用户的界面</font></h1></center>
<br/>
<br/>
<form action="empProcess.php" method="post">
<table align="center" cellpadding="10px"> <tr align="center">
<td>请输入姓名:</td>
<td><input type="text" name="name"/></td>
</tr> <tr align="center">
<td>请输入您的等级:</td>
<td><input type="text" name="grade"/></td>
</tr> <tr align="center">
<td>请输入您的邮箱:</td>
<td><input type="text" name="email"/></td>
</tr> <tr align="center">
<td>请输入您的薪水:</td>
<td><input type="text" name="salary"/></td>
</tr>
<input type="hidden" name="type" value="add"/>
<tr align="center">
<td><input type="submit" name="submit" value="单击提交" /></td>
<td><input type="reset" name="reset" value="重新输入" /></td>
</tr>
<tr>
<td colspan="2"><a href="empMain.php?name=admin">单击返回上一级</a></td>
</tr>
</table>
</form>
</body>
</html>

Admin.class.php

 <?php
class Admin
{
private $id;
private $name;
private $password;
public function getid()
{
return $this->id;
}
public function setid($id)
{
$this->id=id;
}
public function getname()
{
return $this->name;
}
public function setname($name)
{
$this->name=$name;
}
public function getpassword()
{
return $this->password;
}
public function setpassword($password)
{
$this->password=$password;
}
}
?>

AdminService.class.php

 <?php
require_once 'SqlHelper.class.php';
class AdminService
{
public function checkAdmin($get_id,$get_password)
{
$sql="select password from admin where id='".$get_id."'";
//建立一个SqlHelper.class.php对象
$sqlhelper=new SqlHelper("localhost","root","5a6f38","empmanage");
$res=$sqlhelper->dql($sql);
$row=mysql_fetch_assoc($res);
mysql_free_result($res);
mysql_close($sqlhelper->conn);
if($row)
{
$password=$row['password'];
if(md5($get_password)==$password)
{
return 1;
}
return 0;
}
return 0;
}
public function getName($id)
{
$sqlhelper=new SqlHelper("localhost","root","5a6f38","empmanage");
$sql="select name from admin where id='".$id."'";
$res=$sqlhelper->dql($sql);
$row=mysql_fetch_assoc($res);
if($row)
{
mysql_free_result($res);
mysql_close($sqlhelper->conn);
return $row['name'];
}
die("查无此人!");
}
}
?>

checkCode.php

 <?php
//首先定义一个空字符串
$checkCode="";
//随机生成四个数并拼接起来
for($i=1;$i<=4;$i++)
{
$checkCode.=rand(0,9);
}
session_start();
$_SESSION['checkCode']=$checkCode;
//开始绘制验证码 //1.生成画布
$im=imagecreatetruecolor(45,25);
//2.随机生成一个颜色
$color=imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));
//$color=imagecolorallocate($im,255,0,0); //3.绘制干扰线
for($i=1;$i<=20;$i++)
{
imageline($im,0,rand(0,24),44,rand(0,24),imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255)));
}
//4.绘制字符串
imagestring($im,5,3,3,$checkCode,$color);
header("content-type: image/png");
imagepng($im); //4.销毁图片
imagedestroy($im);
?>

common.php

 <?php
/**
* 这个方法专门用于用户判断
*/
function checkUser()
{
session_start();
if(empty($_SESSION['name']))
{
header("Location:login.php?error=请先登录在进行其他操作!");
exit();
}
}
/**
* 这个类中专门存放公共的方法,如取cookie等行为
*/
function getUserName()
{
if(!empty($_COOKIE['name']))
{
return $_COOKIE['name'];
}
else
{
return "";
}
}
function getPassword()
{
if(!empty($_COOKIE['password']))
{
return $_COOKIE['password'];
}
else
{
return "";
}
}
function getLastTime()
{
date_default_timezone_set("Asia/Chongqing");
if(empty($_COOKIE['lasttime']))
{
setCookie("lasttime",date("Y年m月d日 H时m分s秒"),Time()+14*24*3600);
echo "您是第一次登陆本系统!";
}
else
{
setCookie("lasttime",date("Y年m月d日 H时m分s秒"),Time()+14*24*3600);
echo "您上一次的登录时间是:".$_COOKIE['lasttime'];
}
}
?>

Emp.class.php

 <?php
class Emp
{
private $id;
private $name;
private $grade;
private $email;
private $salary;
public function setid($id)
{
$this->id=$id;
}
public function getid()
{
return $this->id;
}
public function setname($name)
{
$this->name=$name;
}
public function getname()
{
return $this->name;
}
public function setgrade($grade)
{
$this->grade=$grade;
}
public function getgrade()
{
return $this->grade;
}
public function setemail($email)
{
$this->email=$email;
}
public function getemail()
{
return $this->email;
}
public function setsalary($salary)
{
$this->salary=$salary;
}
public function getsalary()
{
return $this->salary;
}
}
?>

empList.php

 <?php
/**
* 进行用户验证
*/
require_once 'common.php';
checkUser();
?>
<html>
<head>
<script type="text/javascript">
function confirmDel(val)
{
return window.confirm("确认删除"+val+"号雇员吗?");
}
</script>
</head>
<body>
<?php
require_once 'EmpService.class.php';
//本子功能主要知识点:分页管理功能,可以使用死去活来法逐步实现。
echo "<center>";
echo "<h1>用户管理</h1><br/>";
$empservice=new EmpService();
//获取emp表的记录数。
$rowCount=$empservice->getRowCount();
//设置pageNow的默认值。
$pageNow=1;
//获取pageNow的值
if($_GET['pageNow'])
{
$pageNow=$_GET['pageNow'];
}
//设置$pageSize的默认值,可以由用户自定义
$pageSize=7;
//计算pageCount的值
$pageCount=ceil($rowCount/$pageSize);
if($pageNow<=0)
{
echo "访问出现上溢,自动跳转到第一页!<br/><br/>";
$pageNow=1;
}
else if($pageNow>=($pageCount+1))
{
echo "访问出现下溢,自动跳转到最后一页!<br/><br/>";
$pageNow=$pageCount;
}
$arr_res=$empservice->getResource($pageNow, $pageSize);
$rows=mysql_affected_rows($empservice->getSqlHelper()->conn);
$cols=mysql_num_fields($empservice->getResource_unArray()); echo "<table bgcolor=black rows=".($rows+1)." cols=".($cols+2)." cellspacing=1px cellpadding=10px>";
echo "<tr bgcolor=white>";
for($i=0;$i<$cols;$i++)
{
echo "<th>".mysql_field_name($empservice->getResource_unArray(),$i)."</th>";
}
echo "<th>修改用户信息</th>";
echo "<th>删除用户</th>";
echo "</tr>";
for($i=0;$i<count($arr_res);$i++)
{
$row=$arr_res[$i];
echo "<tr bgcolor=white>";
foreach($row as $key=>$value)
{
echo "<td align=center>".$value."</td>";
}
echo "<td align=center><a href='updateEmpUI.php?id={$row['id']}'>修改</a></td>";
echo "<td align=center><a onclick=
'return confirmDel({$row['id']})'
href='empProcess.php?type=del&id={$row['id']}
&pageNow={$pageNow}'>删除</a></td>";
echo "</tr>";
}
echo "</table><br/>";
$empservice->closeAll();
echo "<a href='empList.php?pageNow=1'>首页</a>&nbsp;&nbsp;&nbsp;";
if($pageNow>=2)
{
echo "<a href='empList.php?pageNow=".($pageNow-1)."'>上一页</a>&nbsp;&nbsp;&nbsp;";
}
else
{
echo "上一页&nbsp;&nbsp;&nbsp;";
}
//一下将会实现6页6页的整体翻页。
$index=floor(($pageNow-1)/6)*6+1;
$start=$index;
echo "<a href='empList.php?pageNow=".($start-1)."'><<</a>&nbsp;&nbsp;&nbsp;";
for(;$start<=5+$index;$start++)
{
if($start<=$pageCount)
{
echo "<a href='empList.php?pageNow=".$start."'>[".$start."]";
echo "</a>"."&nbsp;&nbsp;&nbsp;";
}
else
{
$start--;
break;
}
}
/**
* 如果有6条记录,现在是第2条,那么2/6=0.33,floor(0.33)==0,
* ...什么时候打印?求打印条件。
*/
echo "...&nbsp;&nbsp;&nbsp;";
echo "[当前页{$pageNow}/共{$pageCount}页]&nbsp;&nbsp;&nbsp;";
echo "<a href='empList.php?pageNow=".$start."'>>></a>&nbsp;&nbsp;&nbsp;";
if($pageNow<=($pageCount-1))
{
echo "<a href='empList.php?pageNow=".($pageNow+1)."'>后一页</a>&nbsp;&nbsp;&nbsp;";
}
else
{
echo "后一页&nbsp;&nbsp;&nbsp;";
}
echo "<a href='empList.php?pageNow=".$pageCount."'>尾页</a>";
echo "<br/>";
?>
<br/>
<form action="empList.php" method="get">
请输入跳转页:<input type="text" name="pageNow"/>
<input type="submit" value="GO"/>
</form> </body>
</html>

empMain.php

 <?php

 /**
* 进行用户验证
*/
require_once 'common.php';
checkUser(); $admin_name=$_GET['name'];
require_once 'common.php';
getLastTime();
echo "<center>";
if(!$admin_name)
{
die("没有收到用户名数据!");
}
else
{
echo "<font size='7'>".$admin_name.",欢迎您登陆本系统!<br/><br/>";
echo "</font>";
} echo "<font size='5'>";
echo "<a href='empList.php'>管理用户</a><br/><br/>";
echo "<a href='addEmp.php'>添加用户</a></a><br/><br/>";
echo "<a href='#'>等待添加</a></a><br/><br/>";
echo "<a href='#'>等待添加</a></a><br/><br/>";
echo "</font size='5'>";
echo "</center>";
?>

empProcess.php

 <?php
/**
* 进行用户验证
*/
require_once 'common.php';
checkUser(); require_once 'EmpService.class.php'; $type=$_REQUEST['type'];
if($type=="del")
{
$id=$_GET['id'];
$pageNow=$_GET['pageNow'];
if(empty($id))
{
die("没有收到雇员的ID号数据!");
}
//创建一个EmpService的对象
$empservice=new EmpService();
$flag=$empservice->deleteUser($id);
if($flag==1)
{
header("Location:success.php?id={$id}&pageNow={$pageNow}");
exit();
}
header("Location:error.php?id={$id}");
exit();
}
else
if($type=="add")
{
$empService=new EmpService();
$name=$_POST['name'];
$grade=$_POST['grade'];
$email=$_POST['email'];
$salary=$_POST['salary'];
$result=$empService->addEmp($name, $grade, $email, $salary);
if($result!=1)
{
die("添加用户失败!".mysql_errno());
}
else
{
echo "添加成功!<a href='addEmp.php'>返回上一级</a>";
}
}
else
if($type=="update")
{
$empService=new EmpService();
$id=$_POST['id'];
$name=$_POST['name'];
$grade=$_POST['grade'];
$email=$_POST['email'];
$salary=$_POST['salary'];
$result=$empService->updateEmp($name, $grade, $email, $salary,$id);
if($result!=1)
{
die("更新用户信息失败!".mysql_errno());
}
else
{
echo "更新用户信息成功!<a href='updateEmpUI.php?id={$id}'>返回上一级</a>";
}
} ?>

EmpService.class.php

 <?php
require_once 'SqlHelper.class.php';
require_once 'Emp.class.php';
class EmpService
{
private $sqlhelper;
private $res;
public function __construct()
{
$this->sqlhelper=new SqlHelper("localhost","root","5a6f38", "empmanage");
}
/**
* 这个方法专门用于更新雇员信息
*/
public function updateEmp($name, $grade, $email, $salary,$id)
{
$sql="update emp set name='{$name}',grade={$grade},
email='{$email}',salary={$salary} where id={$id}";
$result=$this->sqlhelper->dml($sql);
mysql_close($this->sqlhelper->conn);
return $result;
}
/**
* 这个方法通过ID号取得雇员的其他信息
*/
public function getEmpById($id)
{
$emp=new Emp();
$sql="select * from emp where id={$id}";
$this->res=$this->sqlhelper->dql($sql);
if(!$this->res)
{
die("查询失败!".mysql_errno());
}
if(($row=mysql_fetch_assoc($this->res))!=null)
{
$emp->setid($row['id']);
$emp->setemail($row['email']);
$emp->setgrade($row['grade']);
$emp->setname($row['name']);
$emp->setsalary($row['salary']);
}
$this->closeAll();
return $emp;
}
/**
* 这个方法是专门针对添加用户的方法
*/
public function addEmp($name,$grade,$email,$salary)
{
$sql="insert into emp(name,grade,email,salary) values ('{$name}',{$grade},'{$email}',{$salary})";
//$this->sqlhelper=new SqlHelper("localhost", "root","5a6f38", "empmanage");
$result=$this->sqlhelper->dml($sql);
mysql_close($this->sqlhelper->conn);
return $result;
}
public function getRowCount()
{
$sql="select count(*) from emp";
$res=$this->sqlhelper->dql($sql);
if(!$res)
{
die("查询失败!");
}
$row=mysql_fetch_row($res);
$rowCount=$row[0];
return $rowCount;
}
public function getResource($pageNow,$pageSize)
{
$x=($pageNow-1)*$pageSize;
$sql="select * from emp order by id limit ".$x.",".$pageSize;
$res=mysql_query($sql,$this->sqlhelper->conn);
$this->res=$res;
if(!$res)
{
die("获取资源失败!");
}
$arr=Array();//效仿discuz的写法,这是05版本的改进之处。
$top=-1;
while(($row=mysql_fetch_assoc($res))!=null)
{
$arr[++$top]=$row;
}
return $arr;
}
public function getSqlHelper()
{
return $this->sqlhelper;
}
public function getResource_unArray()
{
return $this->res;
}
public function closeAll()
{
mysql_free_result($this->res);
mysql_close($this->sqlhelper->conn);
}
public function closeConn()
{
mysql_close($this->sqlhelper->conn);
}
public function deleteUser(&$id)
{
$sql="delete from emp where id={$id}";
return $this->sqlhelper->dml($sql);
}
}
?>

error.php

 <?php
echo "删除失败!";
?>

loginProcess.php

 <?php
// print_r($_COOKIE);
require_once 'AdminService.class.php';
$admin_id=$_POST['admin_id'];
$admin_password=$_POST['admin_password'];
$userinf=$_POST['userinf'];//记录用户是否要求浏览器记住用户密码
$checkCode=$_POST['checkCode'];
session_start(); if($checkCode!=$_SESSION['checkCode'])
{
header("Location:login.php?error=验证码输入错误,请重新输入!");
exit();
}
if(empty($userinf))//用户不允许记住用户名和密码
{
// echo "用户不允许记住账号密码<br/>";
//查看以前是否有cookie记录,如果有,则删除全部
if(!empty($_COOKIE['name']))
{
// echo "将会删除cookie<br/>";
setCookie("name",$admin_id,Time()-14*24*3600);
setCookie("password",$admin_password,Time()-14*24*3600);
setCookie("lasttime",date("Y年m月d日 H时m分s秒"),Time()-14*24*3600);
}
}
else //用户允许记住用户名和密码
{
// echo "用户允许浏览器记住账号密码<br/>";
//先查看cookie中是否有以前的记录,如果有,显示上一次登录的时间;反之
//提示是首次登陆,并保存住账号密码
if(empty($_COOKIE['name']))//
{
// echo "将会创建cookie<br/>";
setCookie("name",$admin_id,Time()+14*24*3600);
setCookie("password",$admin_password,Time()+14*24*3600);
}
}
// exit(); $adminservice=new AdminService();
$flag=$adminservice->checkAdmin($admin_id, $admin_password);
if($flag==1)
{
session_start();
/**
将数据保存到session中,进行用户登录校验
*/
$_SESSION['name']=$admin_id;
header("Location:empMain.php?name=".$adminservice->getName($admin_id));
exit();
}
else
{
header("Location:login.php?error=用户名或者密码错误,请重新输入!");
exit();
}
?>

SqlHelper.class.php

 <?php
class SqlHelper
{
public $host;
public $user;
public $psw;
public $dbname;
public $conn;
public function __construct($host,$user,$psw,$dbname)
{
$this->host=$host;
$this->user=$user;
$this->psw=$psw;
$this->dbname=$dbname;
$this->conn=mysql_connect($this->host,$this->user,$this->psw);
if(!$this->conn)
{
die("数据库连接失败!".mysql_error());
}
mysql_select_db($this->dbname);
mysql_query("set names utf8",$this->conn);
}
public function dql($sql)
{
$res=mysql_query($sql,$this->conn);
if(!$res)
{
die("查询失败!".mysql_error());
}
else return $res;
}
public function dml($sql)
{
$res=mysql_query($sql,$this->conn);
if(!$res)
{
die("数据更新失败!".mysql_error());
}
else if(mysql_affected_rows($this->conn))
{
return 1;
}
else
{
return 2;
}
}
}
?>

success.php

 <?php
$pageNow=$_GET['pageNow'];
echo "删除成功!";
echo "<a href='empList.php?pageNow={$pageNow}'>返回上一级</a>";
?>

updateEmpUI.php

 <?php
/**
* 进行用户验证
*/
require_once 'common.php';
checkUser();
?>
<html>
<!--这个是专门针对更新用户信息设计的界面-->
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
</head>
<body>
<?php
require_once 'Emp.class.php';
require_once 'EmpService.class.php';
$id=$_GET['id'];
//获得其他参数。
$empService=new EmpService();
//获取Emp对象。
$emp=$empService->getEmpById($id);
?>
<center><h1><font size='30px'>这里是更新用户信息的界面</font></h1></center>
<br/>
<br/>
<form action="empProcess.php" method="post">
<table align="center" cellpadding="10px">
<tr align="center">
<td>您的ID是:</td>
<td><input readonly="readonly" type="text" name="id" value="<?php echo $emp->getid()?>"/></td>
</tr> <tr align="center">
<td>请输入您的新姓名:</td>
<td><input type="text" name="name" value="<?php echo $emp->getname()?>"/></td>
</tr> <tr align="center">
<td>请输入您的新等级:</td>
<td><input type="text" name="grade" value="<?php echo $emp->getgrade()?>"/></td>
</tr> <tr align="center">
<td>请输入您的新邮箱:</td>
<td><input type="text" name="email" value="<?php echo $emp->getemail()?>"/></td>
</tr> <tr align="center">
<td>请输入您的新薪水:</td>
<td><input type="text" name="salary" value="<?php echo $emp->getsalary()?>"/></td>
</tr>
<input type="hidden" name="type" value="update"/>
<tr align="center">
<td><input type="submit" name="submit" value="单击提交" /></td>
<td><input type="reset" name="reset" value="重新输入" /></td>
</tr>
<tr>
<td colspan="2"><a href="empMain.php?name=admin">单击返回上一级</a></td>
</tr>
</table>
</form>
</body>
</html>

这个小项目还只是个半成品。仅仅完成了对雇员的增删改功能,查找功能还未实现。但是实现了cookie、session、验证码的小功能。特别是小项目是采用的mvc架构,这就大大增加了开发难度但是代码复用性大大提高了。

项目截图:

【PHP小项目使用MVC架构】【PHP小项目使用MVC架构】【PHP小项目使用MVC架构】【PHP小项目使用MVC架构】【PHP小项目使用MVC架构】【PHP小项目使用MVC架构】