实现一个迷你的mvc
- 1 安装第三方数据库框架medoo
composer require catfan/medoo
- 2 安装第三方php模板引擎plates
composer require league/plates
- 3 创建框架核心目录core
- 4 创建框架模型类Model.php,使用构造函数连接数据库
<?php
namespace core;
use Medoo\Medoo;
class Model extends Medoo{
public function __construct()
{
parent::__construct(
[
'database_type'=>'mysql',
'database_name'=>'php',
'server'=>'localhost',
'username'=>'root',
'password'=>'123456',
]
);
}
}
- 5 创建框架视图类View.php
<?php
namespace core;
use League\Plates\Engine;
class View extends Engine{
public $templates;
public function __construct($path)
{
$this->templates=parent::__construct($path);
}
}
- 6 创建mvc目录 app/controllers,app/models,app/views
- 7 创建自定义模型类UserModel.php
<?php
namespace models;
use core\Model;
//自定义模型类通常与一张数据表绑定,继承自框架核心模型类
class UserModel extends Model{
public function __construct()
{
parent::__construct();
}
}
- 8 创建控制器UserController.php
<?php
namespace controllers;
class UserController{
public $model;
public $view;
public function __construct($model,$view)
{
$this->model=$model;
$this->view=$view;
}
public function index()
{
return __METHOD__;
}
public function select()
{
//获取数据
$user= $this->model->select('user',['id','name','gender','age','email','borthday','create_time']);
//模板赋值
return $this->view->render('users/list',['users'=>$user]);
}
}
- 9 创建视图users/list.php
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.active{
color: green;
}
a{
text-decoration: none;
color: #000;
}
</style>
</head>
<body>
<table>
<caption>员工列表</caption>
<thead>
<tr>
<th>id</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>邮箱</th>
<th>生日</th>
<th>入职日期</th>
<th>操作</th>
</tr>
<tbody>
<?php foreach($users as $v): ?>
<tr>
<td><?= $v['id'] ?></td>
<td><?= $v['name'] ?></td>
<td><?= $v['age'] ?></td>
<td><?= $v['gender'] ?></td>
<td><?= $v['email'] ?></td>
<td><?= $v['borthday'] ?></td>
<td><?= $v['create_time'] ?></td>
<td><button>编辑</button> <button>删除</button></td>
</tr>
<?php endforeach?>
</tbody>
</thead>
</table>
<p>
</p>
</body>
</html>
- 10 配置composer.json文件 autoload psr-4自动映射
{
"name": "wang/php.cn",
"description": "this is a test",
"require": {
"catfan/medoo": "^1.7",
"league/plates": "^3.4"
},
"autoload": {
"psr-4": {
"models\\": "app/models",
"views\\": "app/views",
"controllers\\": "app/controllers",
"core\\": "core"
}
}
}
- 11 使用compser -dump命令更新映射
- 12 创建入口文件index.php
```
<?php
//入口文件
use controllers\UserController;
use core\View;
use models\UserModel;
require DIR.’/vendor/autoload.php’;
//模型
$model=new UserModel();
//视图
$view=new View(‘app/views’);
//控制器
$controller=new UserController($model,$view);
echo $controller->select();
```
浏览器访问入口文件index.php