码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-03-11 19:33:23      阅读:53      评论:0      收藏:0      [点我收藏+]

标签:stat   one   fetchall   chm   文件路径   include   display   none   public   

目录结构:

技术图片

增加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‘);

    }
}

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

标签:stat   one   fetchall   chm   文件路径   include   display   none   public   

原文地址:https://www.cnblogs.com/xiaobingch/p/12464609.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!