PHP从零开始写MVC(附代码 3kb)

浏览:2679 发布日期:2018/03/30 分类:功能实现 关键字: MVC
mvc简单,3kb完成一个MVC开发模式的实现
mvc简单,3kb完成一个MVC开发模式的实现。
附结构图

首先将目录结构建立好
mylib作为核心文件目录
app是控制器模型模板目录
public是单入口,也就是对外公开目录
单入口文件主要是引入引导文件<?php 
// 定义APP目录
define('APP_PATH', __DIR__ . '/../app/');
// 引入框架
require_once '../mylib/Loader.php';
引导文件主要是注册自动加载并执行APP<?php 
// 设置时区
date_default_timezone_set('PRC');

// 注册自动加载
spl_autoload_register(function($class){
    $class_path = str_replace('\\', DIRECTORY_SEPARATOR, $class);
    if (0 === strpos($class_path, 'mylib')) {
        $file = dirname(__DIR__) . DIRECTORY_SEPARATOR . $class_path . '.php';
    } elseif (0 === strpos($class_path, 'app')) {
        $file = dirname(APP_PATH) . DIRECTORY_SEPARATOR . $class_path . '.php';
    }
    if (is_file($file)) {
        require_once $file;
        if(class_exists($class, false)) {
            return true;
        }
    }
    return false;
});

// 执行APP
\mylib\App::run();
app执行主要是一个简易的MVC实现,就是通过$_GET[]里面的 c找到对应的控制器类 然后执行$_GET['a']传递过来的方法<?php 
namespace mylib;
class App{

    public static function run(){

        $controller = isset($_GET['c'])&&$_GET['c'] ? $_GET['c']:'Index';
        $action = isset($_GET['a'])&&$_GET['a'] ? $_GET['a'] : 'index';

        $class = '\\app\\controller\\' . $controller;

        echo (new $class()) -> $action();
    }
}
到这里 MVC基本功能已经实现了!
然后是写控制器 模型 以及模板代码!
示例控制器:<?php 
namespace app\controller;
class Index {

    public function index(){
//实例化模型
        $model = new \app\model\Content();
        $content = $model -> getContent();
//将模型里面的数据传入到视图类渲染成HTML代码返回
        $view = new \mylib\View();
        $view -> assign('content', $content);
        $tpl = APP_PATH . 'view/index/index.php';
//返回html代码并在APP类里面输出
        return $view -> fetch($tpl);
    }

}
模型类 获取一篇文章<?php 
namespace app\model;
class Content
{
    
    public function getContent(){
        return [
            'title'=>'hello MVC!',
            'body'=>'这是我的第一个PHP学习框架!',
        ];
    }
}
视图渲染基类 主要是存储变量 读取模板文件 渲染后返回html代码<?php 
namespace mylib;
class View
{
    public  $data = [];

    public function __construct() {
    }

    public function assign($field, $value) {
        $this -> data[$field] = $value;
    }

    public function fetch($tpl){
        ob_start();
        ob_implicit_flush(0);
        if (!is_null($this -> data)) {
            extract($this -> data, EXTR_OVERWRITE);
        }
        require $tpl;
        return ob_get_clean();
    }
}
模板<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><?php echo $content['title'] ?></title>
</head>
<body>
    <h1><?php echo $content['title'] ?></h1>
    <p><?php echo $content['body'] ?></p>
</body>
</html>
运行一下:

PHP学习交流群

附件 app.zip ( 2.56 KB 下载:90 次 )

评论( 相关
后面还有条评论,点击查看>>