框架原理之加模型类与视图类
Posted xiaobingch
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了框架原理之加模型类与视图类相关的知识,希望对你有一定的参考价值。
目录结构:
增加model类 corelibmodel.php
<?php
namespace corelib;
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方法 coreMyFrame.php
<?php
namespace core;
class MyFrame
{
public static $classMap = [];
protected $assgin = [];
//运行框架
static function run()
{
p(‘ok‘);
$route = new corelibRoute();
$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文件 appviewsindex.html
<h1>hello views !</h1>
<h2><?= $data ?></h2>
appIndexController.php
<?php
namespace appcontroller;
class IndexController extends coreMyFrame
{
public function index()
{
echo "It‘s Index控制器下的index2方法";
$model = new corelibmodel();
$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‘);
}
}
以上是关于框架原理之加模型类与视图类的主要内容,如果未能解决你的问题,请参考以下文章