自撸框架继承第三方库, 使用第三方类的成员为自己项目增砖添瓦:
自撸PHP发开框架
一.APP项目架构
- M:MODEL, 使用第三方包实现,composer require catfan/medoo
- V:VIEW, 使用第三方包实现,composer require league/plates
- C:CONTROLLER :业务逻辑是写在控制器中
二、开发流程:
1、创建自己的框架核心core, Model和View,继承第三方的组件:
Model ———————————
<?php
//框架核心 模型类
namespace core;
use Medoo\Medoo;
class Model extends Medoo
{
public function __construct()
{
$options = [
'database_type' => 'mysql',
'database_name' => 'study',
'server' => 'localhost',
'username' => 'root',
'password' => '123456'
];
// 继承父类构造方法
parent::__construct($options);
}
}
View ———————————
<?php
//框架核心 视图类
namespace core;
use League\Plates\Engine;
class View extends Engine
{
public $template;
public function __construct($path)
{
$this->template = parent::__construct($path);
}
}
2、创建应用APP,MVC架构,创建应用的 models, views, controllers:
UsersController.php
<?php
namespace controllers;
class UsersController
{
public $model;
public $view;
public function __construct($model,$view)
{
$this->model = $model;
$this->view = $view;
}
public function index()
{
$num = 10;
$page = $_GET['p'] ?? 1;
$offset = ($page - 1) * $num ;
//用户信息总数据
$orders = $this->model->select('order',['id','name','pro','price'],['LIMIT'=>[$offset,$num]]);
//数据表总数据条数
$count = $this->model->count('order');
//获取总页数
$pages = ceil($count/ $num );
//将数据渲染到模板上(模板赋值同步完成)
return $this->view->render('user/list',["pages"=>$pages,"orders"=>$orders,"page"=>$page]);
}
}
UsersModel.php
<?php
namespace models;
use core\Model;
//用户自定义模型通常跟一张数据表对应
class UsersModel extends Model
{
public function __construct()
{
parent::__construct();
}
}
Views>user>list.php,不含分页代码
分页代码查看:PHP原生态!控制+模型+列表渲染+算法分页
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>工人信息数据显示</title>
<link rel="stylesheet" href="./public/static/css/style.css">
</head>
<body>
<table>
<caption>工人信息表</caption>
<thead>
<tr>
<td>编号</td>
<td>姓名</td>
<td>技能</td>
<td>价格</td>
<td>操作</td>
</tr>
</thead>
<tbody>
<?php foreach($orders as $order):?>
<tr>
<td><?= $order['id']?></td>
<td><?= $order['name']?></td>
<td><?= $order['pro']?></td>
<td><?= $order['price']?></td>
<td>
<button onclick="location.href='handle.php?action=edit&id=<?=$order['id']?>'">编辑</button>
<button onclick="del(<?=$order['id']?>)">删除</button>
</td>
</tr>
<?php endforeach;?>
</tbody>
</table>
3、应用入口页 index.php:
<?php
//composer 加载器
require __DIR__ . '\\vendor\\autoload.php';
use models\UsersModel;
use core\View;
use controllers\UsersController;
//测试模型
$model = new UsersModel;
// var_dump($model);
//测试视图
$view = new View('app/views');
// var_dump($view);
//测试控制器
$controller = new UsersController($model,$view);
// var_dump($controller);
print_r($controller->index()) ;