框架原理之加模型类与视图类(五)

目录结构:

qq%e5%9b%be%e7%89%8720170523170631

增加model类 \core\lib\model.php

<?php
namespace core\lib;
class model extends \PDO
{
public function __construct()
{
$dsn = 'mysql:host=localhost;dbname=test';
$username = 'root';
$passwd = 'root';
try {
parent::__construct($dsn,$username,$passwd);
} catch (\Exception $e) {
p($e->getMessage());
}
}
}

增加assgin和display方法 core\MyFrame.php

<?php
namespace core;
class MyFrame
{
public static $classMap = [];
protected $assgin = [];
//运行框架
static function run()
{
p('ok');
$route = new \core\lib\Route();
$ctrlClass = $route->controller;
$action = $route->action;
//控制器文件路径
$ctrlFile = APP.'/controller/'.$ctrlClass.'Controller.php';
//控制器类(含namespace)
$ctrlClassNp = '\\'.MODULE.'\\controller\\'.$ctrlClass.'Controller';
if (is_file($ctrlFile)) {
$index = new $ctrlClassNp();
$index->$action();
} else {
throw new \Exception('找不到控制器'.$ctrlClass);
}
}
/*
* 自动加载
*/
static function load($class)
{
if(isset(self::$classMap[$class])) {
return true;
} else {
$file = MYFRAME.'/'.str_replace('\\','/',$class).'.php';
if (is_file($file)) {
require_once $file;
self::$classMap[$class] = $class;
} else {
return false;
}
}
}
/*
* 分配变量
*/
protected function assgin ($name,$value)
{
$this->assgin[$name] = $value;
}
/*
* 渲染模版
*/
protected function display($file)
{
extract($this->assgin);
$file = APP.'/views/'.$file;
if (is_file($file)) {
include $file;
}
}
}

增加view文件 app\views\index.html

<h1>hello views !</h1>
<h2><?= $data ?></h2>

app\IndexController.php

<?php
namespace app\controller;
class IndexController extends \core\MyFrame
{
public function index()
{
echo "It's Index控制器下的index2方法";
$model = new \core\lib\model();
$res = $model->query('select * from test');
$res->setFetchMode(\PDO::FETCH_ASSOC);
p($res->fetchAll());
//分配变量
$this->assgin('data','this is view file!');
//渲染模版
$this->display('index.html');
}
}
posted @   xiaobingch  阅读(210)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示