Blogger Information
Blog 30
fans 1
comment 0
visits 24017
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP框架MVC原理
阿乎乎的学习
Original
977 people have browsed it

MVC的原理是通过解析路由,获得参数,通过参数加载获取相对应的控制器和方法。

index.php实例

<?php
//获得路由地址
$path=$_SERVER['REQUEST_URI'];
$script_name=$_SERVER['SCRIPT_NAME'];
$path=str_replace($script_name,'',$path);
//解析路由
$path=ltrim($path,'/');
//分割获得的参数
$path=explode('/',$path);
//将分割的路由参数第一个字母大写,用来对应控制器
$path[0]=ucfirst($path[0]);
//获取类名
$controller=$path[0];
//获取方法
$method=$path[1];
//加载控制器
include_once __DIR__.'/controller/'.$controller.'Controller.php';
//加载模型
include_once __DIR__.'/model/'.$controller.'Model.php';
$obj=new HomeController();
echo $obj->$method();

运行实例 »

点击 "运行实例" 按钮查看在线实例

controller/HomeController.php实例

<?php
class HomeController {
    public function index(){
        return 'hello world';
    }
    //添加访问视图的方法
    public function view(){
        require __DIR__.'/../view/home.php';
    }
    public function model(){
        //本来还在思考怎么才能用变量动态引入model和view,但是后来一想MVC一个控制器对应一个模型对应一个view,他们是一一对应的,应该不需要动态引入。
        include_once __DIR__.'/../model/HomeModel.php';
        $obj=new HomeModel('小新',18,'男');
        $res=$obj->show();
        return $res;
    }
}

运行实例 »

点击 "运行实例" 按钮查看在线实例

 

model/HomeModel.php实例

这加载的一个模型,但是模型好像不应该这样用!

<?php
class HomeModel{
    public $name;
    public $age;
    public $sex;
    public function show(){
        return '我的名字是'.$this->name.',今年'.$this->age.'岁了,如你所见我是'.$this->sex.'的。';
    }
    public function __construct($name,$age,$sex)
    {
        $this->name=$name;
        $this->sex=$sex;
        $this->age=$age;
    }
}

运行实例 »

点击 "运行实例" 按钮查看在线实例

view/home.php实例

<?php
echo <<<DOC
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>演示视图页面</title>
</head>
<body>
    <h3>这是一个视图页面</h3>
    <div>看到这个页面说明视图加载成功</div>
    
</body>
</html>
DOC;

运行实例 »

点击 "运行实例" 按钮查看在线实例

虽然大致搞懂了MVC加载的原理,MVC设计模式是通过解析路由来获得参数,通过参数来找到对应的控制器和方法,再通过控制器进而控制视图和模型。但依然不会写真正的MVC架构。

另外,composer的安装基本上都是下一步下一步只需要注意安装目录和选择PHP版本,更改了阿里云的全局配置,比较麻烦的是,我这不知道是网络问题还是什么鬼,根本打不开packagist,所以只能手动下载laravel,不过还是慢!!!

 

 

Correction status:qualified

Teacher's comments:现在学到laravel, 尽快跟上
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!