这回课程涉及了几种常见的设计模式,随后通过简单例子讲解了MVC模式的原理及实现方式。
重要知识点:
1. 单例模式:单例模式的创建实例方法要设置成静态的。
要将构造方法( __construct() )及克隆方法( __clone() )进行私有化,杜绝外部实例化类。
2. 工厂模式:就是一个批量创建对象的方法,较易理解。
3. 注册树:就是将预定义好的类挂到树上,即放到一个容器中(一般是数组)的概念。
4. MVC模式是个比较重要的概念,核心在与将数据,视图与业务逻辑分开。
单例模式
一个类只能实例化一次,就是不能从外部进行实例化,
代码实例:
实例
class Config { //这里是静态的,这样可以通过类来访问 private static $instance = null; //不允许从外部实例化类,因此这里要禁止构造方法 //只需要将构造方法私有化就行了 private function __construct() { } //把克隆方法私有化,防止外部复制来进行实例化 private function __clone() { } //外部仅允许通过一个公共静态方法来创建实例 public static function getInstance() { if(self::$instance == null){ self::$instance = new self(); } return self::$instance; } private $setting; public function set() { if(func_num_args() > 0){ switch (func_num_args()) { case 1: if(is_array(func_get_arg(0))) { $this->setting = func_get_arg(0); } break; case 2: $this->setting[func_get_arg(0)] = func_get_arg(1); break; default: echo '传入参数格式错误!!!'; } }else{ echo '没有参数!!!'; } } public function get($name='') { if(empty($name)) { return $this->setting; } return $this->setting[$name]; } } $ins1 = Config::getInstance(); $ins2 = Config::getInstance(); //$ins = new Config();//这里是不能创建对象的 var_dump($ins1,$ins2); echo '<hr>'; $ins1->set('host','127.0.0.1'); print_r($ins1->get());
运行实例 »点击 "运行实例" 按钮查看在线实例
工厂模式
代码实例:
实例
<?php /** * 工厂类,不使用new,而是用函数/方法批量创建对象 */ class Factory { public static function create($type, $size=[]) { switch($type) { case 'rectangle': return new Rectangle($size[0],$size[1]); break; case 'trangle': return new Rectangle($size[0],$size[1]); break; } } } //长方形类 class Rectangle { private $width; private $height; public function __construct($width, $height) { $this->width = $width; $this->height = $height; } public function area() { return $this->width * $this->height; } } // 声明一个三角形类 class Rriangle { private $bottom; // 底 private $height; // 高 public function __construct($bottom, $height) { $this->bottom = $bottom; $this->height = $height; } //计算面积 public function area() { return ($this->bottom * $this->height)/2; } } echo (Factory::create('rectangle',['10','10']))->area();
运行实例 »点击 "运行实例" 按钮查看在线实例
注册树
代码实例:
实例
<?php /** * 注册树: 就是创建一个对象集合/对象池/对象树,对象容器来存储对象 */ class Demo1{}; class Demo2{}; class Demo3{}; class Register { public static $objs; public static function set($index,$obj) { self::$objs[$index] = $obj; } public static function get($index) { return self::$objs[$index]; } public static function del($index) { unset(self::$objs[$index]); } } Register::set('demo1',new Demo1()); Register::del('demo1'); var_dump(Register::get('demo1'));
运行实例 »点击 "运行实例" 按钮查看在线实例
MVC模式设计
mvc是指Model(模型),View(视图),Controller控制器()。
原理:浏览器发出请求发送至controlle中,model中通过数据库访问拿到数据返回给controller,然后将数据渲染到view中,然后将生成好的html文件返回给浏览器。
首先是Model类,该类中放数据库连接及拿数据的操作:
实例
<?php /** * 模型类 */ namespace mvc\model; class Model { public $pdo = null; public $result = []; //连接数据库 public function __construct($dsn, $user, $pass) { $this->pdo = new \PDO($dsn, $user, $pass); } public function select($table, $num) { $stmt = $this->pdo->prepare("SELECT `id`,`name`,`age`,`salary` FROM {$table} LIMIT :num"); $stmt->bindValue(':num', $num, \PDO::PARAM_INT); $stmt->execute(); $this->result = $stmt->fetchAll(\PDO::FETCH_ASSOC); return $this->result; } }
运行实例 »点击 "运行实例" 按钮查看在线实例
接下来是View,类中设计一个模板:
实例
<?php namespace mvc\view; class View { public $data = []; public function __construct($data) { $this->data = $data; } //获取数据 public function getData() { return $this->data; } public function display($data) { $table = '<!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>MVC简介</title> <style> table,th,td{border:1px solid #cccccc; text-align: center; line-height: 2rem;} table{border-collapse: collapse; margin:20px auto; width:500px; padding:10px } table caption{font-size: 1.5rem;} table tr:first-child{ background-color: #00BFFF} </style> </head> <body> <table> <caption></caption> <tr> <th>ID</th> <th>姓名</th> <th>年龄</th> <th>工资</th> </tr>'; foreach ($data as $staff) { $table .= '<tr>'; $table .= '<td>'.$staff['id'].'</td>'; $table .= '<td>'.$staff['name'].'</td>'; $table .= '<td>'.$staff['age'].'</td>'; $table .= '<td>'.$staff['salary'].'</td>'; $table .= '</tr>'; } $table .= '</table></body></html>'; echo $table; } }
运行实例 »点击 "运行实例" 按钮查看在线实例
然后是Controller,对数据及视图进行渲染操作:
实例
<?php namespace mvc\controller; use mvc\view\View; use mvc\model\Model; //spl_autoload_register(function($classname){ // if($classname == 'Model'){ // require './class/'.$classname.'.php'; // }else if($classname == 'View'){ // require './view/'.$classname.'.php'; // } //}); class Controller { public function index() { require './model/Model.php'; $model = new Model('mysql:host=127.0.0.1;dbname=php','root','root'); $model->select('staff', 10); $result = $model->result; require './view/View.php'; $view = new View($result); $data = $view->getData(); $view->display($data); } }
运行实例 »点击 "运行实例" 按钮查看在线实例
最后需要创建一个入口文件(index.php),即调用Controller中方法:
实例
<?php /** * 入口文件 */ require './controller/Controller.php'; use mvc\controller\Controller; $controller = new Controller; $controller->index();
运行实例 »点击 "运行实例" 按钮查看在线实例
得出效果图: