文件结构
Db.php
namespace mvc;
use PDO;
session_start();
ini_set('date.timezone','Asia/Shanghai');
class Db
{
//数据库配置信息
private $dbConfig = [
'db' => 'mysql',
'host' => 'localhost',
'username' => 'root',
'password' => 'root',
'dbname' => 'mvc',
];
//新增主键id
public static $insertId = null;
//受影响的记录数量
public static $num = 0;
//数据库的连接
private static $pdo = null;
//构造方法接收参数
private function __construct(...$params)
{
$dsn = "{$this->dbConfig['db']}:host={$this->dbConfig['host']};dbname={$this->dbConfig['dbname']}";
$username = "{$this->dbConfig['username']}";
$password = "{$this->dbConfig['password']}";
try {
self::$pdo = new PDO($dsn, $username, $password);
} catch (\PDOException $e) {
die('数据库连接失败:' . $e->getMessage());
}
}
//单例模式判断连接
public static function connect(...$params)
{
// 如果没有实例化 就实例化,已经实例化就返回
if (is_null(self::$pdo)){
new self(...$params);
}
return self::$pdo;
}
//禁止外部访问克隆方法
private function __clone()
{
}
// 新增,更新,删除操作
public static function exec($sql)
{
$stmt = self::$pdo->prepare($sql);
$stmt->execute();
if ($stmt->rowCount()>0){
//如果是新增操作,初始化新增主键id属性
if(null !==self::$pdo->lastInsertId()){
self::$insertId = self::$pdo->lastInsertId();
}
self::$num = $stmt->rowCount(); //返回受影响的记录数量
}else {
$error = self::$pdo->errorInfo(); //获取最后操作的错误信息的数组
//[0]错误标识符[1]错误代码[2]错误信息
print '操作失败'.$error[0].':'.$error[1].':'.$error[2];
}
}
//获取单条数据
public static function fetch($sql)
{
$stmt = self::$pdo->prepare($sql);
$stmt->execute();
return $stmt->fetch(PDO::FETCH_ASSOC);
}
//获取多条数据
public static function fetchAll($sql)
{
$stmt = self::$pdo->prepare($sql);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
}
Model.php
namespace mvc;
require 'Db.php';
class Model
{
public $data = null;
//链接数据库
public function __construct()
{
Db::connect();
}
//获取单条数据
public function get($id)
{
$sql = "SELECT * FROM `users` WHERE id = {$id}";
$this->data = Db::fetch($sql);
return $this->data;
}
// 获取多条数据
public function getAll()
{
$sql = "SELECT * FROM `users` WHERE `status` = 1";
$this->data = Db::fetchAll($sql);
return $this->data;
}
//删除单条数据
public function del($id)
{
$sql = "UPDATE `users` SET `status` = 0 WHERE id = {$id}";
$this->data = Db::exec($sql);
return $this->data;
}
}
Controller.php
//控制器
namespace mvc;
require './model/Model.php';
require './view/View.php';
//服务容器
class Container
{
// 创建容器数组,存放实例方法
public $int = null;
//放进去,将类实例化过程绑定到容器
public function bind($alias, \Closure $process)
{
$this->int[$alias] = $process;
}
//取出来,执行容器中的实例方法
public function make($alias, $params = [])
{
//
return call_user_func_array($this->int[$alias], $params);
}
}
$container = new Container();
$container->bind('model', function () {return new Model();});
$container->bind('view', function () {return new View();});
//门面模式
class Facade
{
//接收实例化容器
protected static $container = null;
//绑定数据
protected static $data;
protected static $id;
//用服务容器给它初始化, 将容器注入
public static function initialize(Container $container)
{
static::$container = $container;
}
//将模型中的方法静态化
public static function getAll()
{
static::$data = static::$container->make('model')->getAll();
}
//将模型中的方法静态化--查询单条数据
public static function get($id)
{
static::$id = static::$container->make('model')->get($id);
}
//将模型中的方法静态化--删除单条数据
public static function del($id)
{
static::$id = static::$container->make('model')->del($id);
}
//将模型中的方法静态化--更新数据
public static function update($sql)
{
static::$id = static::$container->make('model')->del($sql);
}
//将视图中的方法静态化
public static function fetch()
{
return static::$container->make('view')->fetch(static::$data);
}
//将视图中的方法静态化--单条数据
public static function find()
{
return static::$container->make('view')->find(static::$id);
}
//将视图中的方法静态化--删除单条数据
public static function del1()
{
return static::$container->make('view')->del1(static::$id);
}
}
//创建控制器
class Controller
{
//初始化,调用 Facade里面的初始化方法
public function __construct(Container $container)
{
Facade::initialize($container);
}
//调用单条数据
public function find($id='')
{
$id = isset($_GET['id']) ? $_GET['id'] : $id;
if (empty($id)){
die('非法操作');
}
//获取数据
Facade::get($id);
//渲染模板
return Facade::find();
}
//调用全部数据
public function getAll()
{
Facade::getAll();
return Facade::fetch();
}
//删除单条数据
public function del1($id='')
{
if(@$_SESSION['name'] != 'admin'){
echo '<script>alert("你不是管理员不能删除数据");history.back();</script>';
exit();
}
$id = isset($_GET['id']) ? $_GET['id'] : $id;
if (empty($id)){
die('非法操作');
}
Facade::del($id);
return Facade::del1();
}
//登录
public function login()
{
require dirname(__DIR__).'/'.'login.php';
}
//验证登录
public function check()
{
require dirname(__DIR__).'/'.'check.php';
}
//退出登录
public function logout()
{
require dirname(__DIR__).'/'.'logout.php';
}
}
$controller = new Controller($container);
View.php
//视图:渲染数据
namespace mvc;
class View
{
//获取所有数据
public function fetch($data)
{
$table = '<table align="center" cellpadding="10">';
$table .= '<caption>学生信息表</caption>';
$table .= '<tr><th>ID</th><th>姓名</th><th>性别</th><th>爱好</th><th>录入时间</th><th>操作</th></tr>';
foreach ($data as $item){
$item['sex'] = $item['sex']==1 ? '男' : '女';
$item['entry_time'] = date('Y-m-d H:i:s',$item['entry_time']);
$table .='<tr>';
$table .='<td>'. $item['id'].'</td>';
$table .='<td>'. $item['name'].'</td>';
$table .='<td>'. $item['sex'] . '</td>';
$table .='<td>'. $item['hobby'].'</td>';
$table .='<td>'. $item['entry_time'].'</td>';
$table .='<td><a href="?a=find&id=' . $item['id'] . '">详细 </a><a href="?a=del1&id=' . $item['id'] . '"> 删除</a></td>';
$table .= '</tr>';
}
$table .= '</table>';
$table .= '<p align="center">共计 ' . count($data). ' 条数据</p> ';
return $table;
}
//获取单条数据
public function find($data)
{
$table = '<table align="center" cellpadding="10">';
$table .= '<caption>学生信息表</caption>';
$table .= '<tr><th>ID</th><th>姓名</th><th>性别</th><th>手机</th>
<th>爱好</th><th>生日</th><th>录入时间</th><th>状态</th></tr>';
$data['sex'] = $data['sex']==1 ? '男' : '女';
$data['entry_time'] = date('Y-m-d H:i:s',$data['entry_time']);
$data['status'] = $data['status']==1 ? '正常' : '已删除';
$table .='<tr>';
$table .='<td>'. $data['id'].'</td>';
$table .='<td>'. $data['name'].'</td>';
$table .='<td>'. $data['sex'] . '</td>';
$table .='<td>'. $data['tel'].'</td>';
$table .='<td>'. $data['hobby'].'</td>';
$table .='<td>'. $data['birthday'].'</td>';
$table .='<td>'. $data['entry_time'].'</td>';
$table .='<td>'. $data['status'].'</td>';
$table .= '</tr>';
$table .= '</table>';
return $table;
}
//删除单条数据
public function del1($data)
{
return '成功删除了' .Db::$num. '条数据';
}
}
echo '<style>
a { text-decoration: none; color: #333;}
table a:first-of-type{ color: red}
table {border-collapse: collapse; border: 1px solid; width: 60%; text-align: center }
caption {font-size: 1.2rem; margin-bottom: 10px;}
tr:first-of-type { background-color:lightblue;}
td,th {border: 1px solid}
td:first-of-type {text-align: center}
</style>';
index.php
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>首页</title>
<style>
body {
text-align: center
}
nav {
width: 60%;
margin: 20px auto;
height: 40px;
background: #444;
line-height: 40px;
padding: 0 20px;
}
nav a {
font-size: 16px;
color: #fff;
padding: 0 10px;
}
</style>
</head>
<body>
<?php
require 'controller/Controller.php';
?>
<nav><a href="/">首页</a>
<?php if (isset($_SESSION['name'])) {
echo '<a >' . $_SESSION['name'] . '</a><a href="index.php?a=logout">退出</a>';
} else {
echo '<a href="index.php?a=login">登录</a>';
} ?>
</nav>
<?php
//获取方法
$a = isset($_GET['a']) ? $_GET['a'] : 'getAll';
//执行控制器方法
echo $controller->$a();
?>
</body>
</html>
login.php
<?php
if(isset($_SESSION['name'])){
echo '<script>alert("你已登录,请不要重复登录");location.assign("index.php");</script>';
}
?>
<h2>用户登陆</h2>
<form action="index.php?a=check" method="post">
<p>
用户名:<input type="text" name="name">
</p><p>
密码:<input type="password" name="pwd">
</p>
<p>
<input type="submit" value="提交">
</p>
</form>
check.php
namespace mvc;
//print_r($_SERVER);
if ($_SERVER['REQUEST_METHOD'] === 'POST'){
$name = $_POST['name'];
$pwd = md5($_POST['pwd']);
Db::connect();
$sql = "SELECT * FROM `admin` WHERE `username` = '{$name}' AND `password` = '{$pwd}'";
$user = Db::fetch($sql);
if(false === $user){
echo '<script>alert("账号或密码错误");history.back();</script>';
die();
}
$_SESSION['name'] = $user['username'];
echo '<script>alert("登录成功");location.assign("index.php");</script>';
exit();
}else{
die("非法操作");
}
logout.php
if(isset($_SESSION['name'])){
session_destroy();
echo '<script>alert("退出成功");location.assign("index.php");</script>';
}else{
echo '<script>alert("请先登录");location.assign("login.php");</script>';
// echo '<script>alert("请先登录");location.assign("login.php");</script>';
}
总结
- 又看了几遍老师录的从零开始开发框架,模仿着写,总算跑起来了。写的很乱,很lower,修改数据和添加数据传参没有思路,还不知道怎么下手。