一、什么是MVC?(这里先浅显介绍)
视图(The View):
一说到视图,我们很多人都会想到模板引擎(诸如Smarty等等)。其实就是各种各样的输出,比如说html模板和Javascript文件等。
模块(The Model):
模块代表了程序的逻辑,在企业应用中通常称为业务逻辑层。一般来讲,这一层完成的工作是把原始的数据处理成按照我们设计的数据结构存储的有意义的数据序列,并将这些数据交给视图去处理。通常情况下, 模块中会利用一个数据抽象类来进行与数据操作有关的处理。
Model通常包含了哪些用来同数据库打交道的函数。
控制器(The Controller):
控制器使所有WEB应用的第一站,他接受收到的参数,比如$_GET变量,然后做出相应的反应。
二、代码(Controller.php Model.php View.php三个文件)
View.php
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2015/4/22
* Time: 9:53
*/
class View {
public function display($output) {
echo $output;
}
}
Model.php
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2015/4/22
* Time: 9:53
*/
header('Content-Type:text/html; charset=utf-8');
class Model {
private $database = array(
'a' => 'hello world',
'b' => 'ok well done',
'c' => 'good bye',
);
// run the query and get the result
public function getResult($name) {
if(empty($name)) {
return false;
}
if(in_array($name, array_keys($this->database))) {
return $this->database[$name];
}
}
// return links view
public function getLinks() {
$links = "<a href='http://www.baidu.com' target='_blank'>百度</a> ";
$links.= "<a href='http://www.sina.com.cn' target='_blank'>新浪</a> ";
$links.= "<a href='http://www.yahoo.com' target='_blank'>雅虎</a> ";
return $links;
}
}
知识点:
/*
* 知识点:
* 1、header('Content-Type:text/html;charset=utf-8'); 声名内容类型和字符集
* 2、public(公共的)可以内部调用,实例调用等
* protected(受保护的)用于本类和继承类调用,实例化调用会报错
* private(私有的)只有在本类中使用,实例化调用会报错
* static(静态的)类不需实例即可调用静态属性或方法
* 3、in_array(search, array, [type]);搜索数组中是否存在指定的值
* 4、array_keys(array, [value], [strict]); 返回包含数组中所有键名的一个新数组
* */
Controller.php
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2015/4/22
* Time: 9:53
*/
include 'Model.php';
include 'View.php';
class Controller {
private $model = '';
private $view = '';
public function Controller() {
$this->model = new Model();
$this->view = new View();
}
public function doAction($method = 'defaultMethod', $param = array()) {
if(empty($method)) {
$this->defaultMethod();
} else if(method_exists($this, $method)) {
call_user_func(array($this, $method), $param);
} else {
$this->nonexisting_method();
}
}
public function link_page($name = '') {
$links = $this->model->getLinks(); // 获取links字符串
$this->view->display($links); // 输出links字符串
$result = $this->model->getResult($name);
$this->view->display($result);
}
public function defaultMethod() {
$this->br();
echo 'This is the default method';
}
public function nonexisting_method() {
$this->br();
echo 'This is the noexisting method. ';
}
public function br() {
echo '<br />';
}
}
$controller = new Controller();
$controller->doAction('link_page', 'a'); // 返回links链接和hello world
$controller->doAction(); // 输出:This is the default method (没有参数的情况)
知识点:
/*
* 知识点:
* 1、method_exists(object, method_name) 检查类的方法是否存在
* 2、call_user_func(callback, parameter) 把第一个参数作用回调函数调用
* 3、empty() 检测变量是否为空、为0
* isset()判断变量是否已声明
* */
三、浏览器访问
四、总结:
希望通过原生php的MVC写法,让大家有个简单的理解,代码复制可用。
如有疑问,敬请留言。
欢迎关注技术开发分享录:http://fenxianglu.cn/