1. 目录结构
2. 代码文件
Db.php
<?php
// 定义命名空间
namespace goods\model;
// 引入外部类的别名
use PDO;
use PDOException;
// 数据库连接类
// 用单例模式实现
class Db
{
// 连接属性
public static $pdo = null;
// 连接方法
private function connect()
{
try {
self::$pdo = new PDO('mysql:host=localhost;dbname=test','root','root');
}catch (PDOException $e){
die('数据库连接失败,错误信息为:' . $e->getMessage());
}
}
// 构造方法私有化
private function __construct()
{
$this->connect();
}
public static function getInstance()
{
if (is_null(self::$pdo)){
new self();
}
return self::$pdo;
}
// 禁用克隆魔术方法
private function __clone()
{
}
}
Model.php
<?php
namespace goods\model;
require 'Db.php';
use PDO;
// 公共模型类
class Model
{
public $pdo = null;
// 该属性用于获取本类的类名
public $className = self::class;
// 构造方法实现数据库连接
public function __construct()
{
$this->pdo = Db::getInstance();
}
// 查询多条记录
public function select($table, $where = '', $order = '', $limit = '')
{
// 创建SQL语句
$sql = 'SELECT * FROM ' . $table;
// 查询条件
if (!empty($where)) {
$sql .= ' WHERE ' . $where;
}
// 排序方式
if (!empty($order)) {
$sql .= ' ORDER BY ' . $order;
}
// 分页
if (!empty($limit)) {
$sql .= ' LIMIT ' . $limit;
}
$sql .= ';';
// 创建PDO预处理对象
$stmt = $this->pdo->prepare($sql);
// 执行查询操作
if ($stmt->execute()) {
if ($stmt->rowCount() > 0) {
$stmt->setFetchMode(PDO::FETCH_CLASS, $this->className);
return $stmt->fetchAll();
}
}
return '查询失败';
}
// 查询单条
public function find($table, $where = '')
{
$sql = 'SELECT * FROM ' . $table;
if (!empty($where)) {
$sql .= ' WHERE ' . $where;
}
$sql .= ' LIMIT 1;';
$stmt = $this->pdo->prepare($sql);
if ($stmt->execute()) {
if ($stmt->rowCount() > 0) {
$stmt->setFetchMode(PDO::FETCH_CLASS, $this->className);
return $stmt->fetch();
}
}
return '查询失败';
}
// 新增记录
public function insert($table, $data = [])
{
$sql = 'INSERT INTO ' . $table . ' SET ';
if (is_array($data)) {
foreach ($data as $k => $v) {
$sql .= "{$k}='{$v}', ";
}
} else {
return '要以关联数组形式传入数据';
}
$sql = rtrim(trim($sql), ',') . ';';
$stmt = $this->pdo->prepare($sql);
if ($stmt->execute()) {
if ($stmt->rowCount() > 0) {
return '添加成功了' . $stmt->rowCount() . '条数据';
}
}
return '添加失败';
}
// 更新数据
public function update($table, $data = [], $where = '')
{
$sql = "UPDATE {$table} SET ";
if (is_array($data)) {
foreach ($data as $k => $v) {
$sql .= "{$k}='{$v}', ";
}
}
$sql = rtrim(trim($sql), ',');
if (!empty($where)) {
$sql .= ' WHERE ' . $where;
}
$stmt = $this->pdo->prepare($sql);
if ($stmt->execute()) {
if ($stmt->rowCount() > 0) {
return '成功修改了' . $stmt->rowCount() . '条数据';
}
}
return '修改失败';
}
// 删除数据
public function delete($table, $where = '')
{
$sql = 'DELETE FROM ' . $table;
if (!empty($where)) {
$sql .= ' WHERE ' . $where;
}
$stmt = $this->pdo->prepare($sql);
if ($stmt->execute()) {
if ($stmt->rowCount() > 0) {
return '删除成功了' . $stmt->rowCount() . '条数据';
}
}
return '删除失败';
}
public function __destruct()
{
$this->pdo = null;
}
}
Goods.php
<?php
namespace goods\model;
require 'Model.php';
// 商品类
class Goods extends Model
{
public $className = self::class;
private $id;
private $name;
private $price;
private $color;
private $content;
private $addtime;
private $status;
public function __construct()
{
parent::__construct();
$this->addtime = date('Y/m/d',$this->addtime);
}
public function __get($name)
{
return $this->$name;
}
public function __set($name, $value)
{
$this->$name = $value;
}
}
View.php
<?php
namespace goods\view;
// 视图类
class View
{
public function showData($data)
{
return $data;
}
public function showTable($data)
{
$table = '<table>';
$table .= '<caption>商品信息表</caption>';
$table .= '<tr><th>商品ID</th><th>商品名称</th><th>商品价格</th><th>商品颜色</th><th>商品描述</th><th>添加时间</th><th>操作</th></tr>';
if (is_array($data)) {
foreach ($data as $value){
$table .= '<tr>';
$table .= '<td>' . $value->id . '</td>';
$table .= '<td>' . $value->name . '</td>';
$table .= '<td>' . $value->price . '</td>';
$table .= '<td>' . $value->color . '</td>';
$table .= '<td>' . $value->content . '</td>';
$table .= '<td>' . $value->addtime . '</td>';
$table .= '<td><a href="./update.php?id=' . $value->id . '" style="margin-right: 20px">修改</a><a href="?id= '. $value->id . '&&func=delete">删除</a></td>';
$table .= '</tr>';
}
} else {
$table .= '<tr>';
$table .= '<td>' . $data->id . '</td>';
$table .= '<td>' . $data->name . '</td>';
$table .= '<td>' . $data->price . '</td>';
$table .= '<td>' . $data->color . '</td>';
$table .= '<td>' . $data->content . '</td>';
$table .= '<td>' . $data->addtime . '</td>';
$table .= '<td><a href="./update.php?id=' . $data->id . '" style="margin-right: 20px">修改</a><a href="?id= '. $data->id . '&&func=delete">删除</a></td>';
$table .= '</tr>';
}
$table .= '</table>';
return $table;
}
public function showResult($result)
{
return '<h4>' . $result . '</h4>';
}
}
echo '<style>
table {
border-collapse: collapse;
border: 1px solid;
margin: 0 auto;
}
caption {
font-size: 1.4rem;
margin-bottom: 10px;
}
tr:first-of-type {
background-color: lightseagreen;
}
th {
height: 40px;
}
td, th {
border: 1px solid;
min-width: 100px;
}
img {
width: 100px;
height: 100px;
}
</style>';
Container.php
<?php
namespace goods\controller;
use Closure;
// 服务容器类
class Container
{
// 容器属性:用来保存创建对象的方法
protected $instance = [];
// 将类的实例化过程绑定到容器中
public function bind($alias, Closure $process)
{
$this->instance[$alias] = $process;
}
// 执行容器中的实例化方法
public function make($alias,$params = [])
{
return call_user_func_array($this->instance[$alias],$params);
}
}
Facade.php
<?php
namespace goods\controller;
//Facade门面类
class Facade
{
protected static $container = null;
protected static $data = [];
protected static $result = null;
// 用服务容器将静态属性初始化
public static function initialize(Container $container)
{
static::$container = $container;
}
// 用静态代理方式将模型类中的 select() 静态化
public static function select($model, $table, $where = '', $order = '', $limit = '')
{
static::$data = static::$container->make($model)->select($table, $where, $order, $limit);
}
// 用静态代理方式将模型类中的 find() 静态化
public static function find($model, $table, $where = '')
{
static::$data = static::$container->make($model)->find($table, $where);
}
// 用静态代理方式将模型类中的 insert() 静态化
public static function insert($model,$table, $data = [])
{
static::$result = static::$container->make($model)->insert($table,$data);
}
// 用静态代理方式将模型类中的 update() 静态化
public static function update($model,$table, $data = [], $where = '')
{
static::$result = static::$container->make($model)->update($table,$data,$where);
}
// 用静态代理方式将模型类中的 delete() 静态化
public static function delete($model,$table, $where = '')
{
static::$result = static::$container->make($model)->delete($table,$where);
}
// 用静态代理方式将视图类中的 showData() 静态化
public static function showData($view)
{
return static::$container->make($view)->showData(static::$data);
}
// 用静态代理方式将视图类中的 showTable() 静态化
public static function showTable($view)
{
return static::$container->make($view)->showTable(static::$data);
}
// 用静态代理方式将视图类中的 showResult() 静态化
public static function showResult($view)
{
return static::$container->make($view)->showResult(static::$result);
}
}
Controller.php
<?php
namespace goods\controller;
// 控制器类
class Controller
{
// 使用构造方法,自动调用Facade里面的初始化方法
public function __construct(Container $container)
{
Facade::initialize($container);
}
// 查询多条数据
public function select($model, $view, $table, $where = '', $order = '', $limit = '')
{
Facade::select($model, $table, $where, $order, $limit);
return Facade::showTable($view);
}
// 查询一条
public function find($model, $view, $table, $where = '')
{
Facade::find($model, $table, $where);
return Facade::showTable($view);
}
// 查询一条
public function find1($model, $view, $table, $where = '')
{
Facade::find($model, $table, $where);
return Facade::showData($view);
}
// 添加数据
public function insert($model, $view, $table, $data = [])
{
Facade::insert($model, $table, $data);
return Facade::showResult($view);
}
// 更新数据
public function update($model, $view, $table, $data = [], $where = '')
{
Facade::update($model, $table, $data, $where);
return Facade::showResult($view);
}
// 删除数据
public function delete($model, $view, $table, $where = '')
{
Facade::delete($model, $table, $where);
return Facade::showResult($view);
}
}
autoload.php
<?php
namespace goods;
// 类的自动加载器
spl_autoload_register(function ($className){
$path = str_replace('\\', '/', $className);
require dirname(__DIR__) . DIRECTORY_SEPARATOR . $path . '.php';
});
header.php
<?php
namespace goods;
require __DIR__ . '/autoload.php';
use goods\controller\Container;
use goods\controller\Controller;
use goods\model\Goods;
use goods\view\View;
$container = new Container();
$container->bind('goods', function () {
return new Goods();
});
$container->bind('tb', function () {
return new View();
});
$controller = new Controller($container);
?>
index.php
<?php
require __DIR__ . '/header.php';
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="" method="get" style="text-align: center">
<label for="find">请输入要查找的商品ID</label>
<input type="text" id="find" name="find" value="">
<button>查找</button>
<a href="insert.php"><input type="button" name="insert" value="添加"></a>
</form>
</body>
</html>
<?php
// 查找一条数据
if (!empty($_GET['find'])) {
$find = $_GET['find'];
echo $controller->find('goods','tb','goods','id=' . $find);
} else {
echo $controller->select('goods', 'tb', 'goods');
}
// 删除数据
if (!empty($_GET['func']) && $_GET['func'] == 'delete') {
echo $controller->delete('goods','tb','goods','id=' . $_GET['id']);
}
insert.php
<?php
require __DIR__ . '/header.php';
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form method="post">
<p>
<label for="name">商品名称</label>
<input type="text" id="name" name="name" value="" required>
</p>
<p>
<label for="price">商品价格</label>
<input type="text" id="price" name="price" value="" required>
</p>
<p>
<label for="color">商品颜色</label>
<input type="text" id="color" name="color" value="" required>
</p>
<p>
<label for="content">商品描述</label>
<input type="text" id="content" name="content" value="" required>
</p>
<p>
<label for="addtime">添加时间</label>
<input type="date" id="addtime" name="addtime" value="" required>
</p>
<button>添加</button>
<a href="index.php">返回</a>
</form>
</body>
</html>
<?php
$_POST['addtime'] = strtotime($_POST['addtime']);
echo $controller->insert('goods','tb','goods',$_POST);
?>
update.php
<?php
require __DIR__ . '/header.php';
if (!empty($_GET['id'])) {
$result = $controller->find1('goods', 'tb', 'goods', 'id=' . $_GET['id']);
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form method="post">
<p>
<label for="name">商品名称</label>
<input type="text" id="name" name="name" value="<?php echo $result->name;?>" required>
</p>
<p>
<label for="price">商品价格</label>
<input type="text" id="price" name="price" value="<?php echo $result->price;?>" required>
</p>
<p>
<label for="color">商品颜色</label>
<input type="text" id="color" name="color" value="<?php echo $result->color;?>" required>
</p>
<p>
<label for="content">商品描述</label>
<input type="text" id="content" name="content" value="<?php echo $result->content;?>" required>
</p>
<p>
<label for="addtime">添加时间</label>
<input type="date" id="addtime" name="addtime" value="<?php echo $result->addtime;?>" required>
</p>
<button>修改</button>
<a href="index.php">返回</a>
</form>
</body>
</html>
<?php
$_POST['addtime'] = strtotime($_POST['addtime']);
echo $controller->update('goods','tb','goods',$_POST,'id=' . $_GET['id']);
?>
3. 运行效果
4. 总结
经过了几天努力,总算实现了,虽然很简单,但对MVC有了很深刻的理解。