今天学习了设计模式与MVC初步的知识,
代码:
实例
<?php //单例模式:一个类只允许被实例化 class Config{ private static $instance=null; private function __construct() { } private function __clone() { // TODO: Implement __clone() method. } public static function getInstance(){ if(self::$instance==null){ self::$instance=new self(); } return self::$instance; } } $c1=Config::getInstance(); $c2=Config::getInstance(); var_dump($c1===$c2);
运行实例 »
点击 "运行实例" 按钮查看在线实例
实例
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2018/9/10 * Time: 16:06 */ namespace MVC\controller; use MVC\model\Model; use MVC\view\View; class Controller { public function index() { require './model/Model.php'; $model = new Model('php', 'root', 'root'); $model->select('staff', 10); $result = $model->result; require './view/View.php'; $view = new View($result); $data = $view->getData(); $view->display($data); } }
运行实例 »
点击 "运行实例" 按钮查看在线实例
实例
<?php //模型类 namespace MVC\model; class Model { public $pdo = null; //连接数据库 public $result = []; public function __construct($dbname, $user, $pass) { $this->pdo = new \PDO('mysql:host=127.0.0.1;dbname='.$dbname, $user, $pass); } //查询 public function select($table, $num) { //创建预处理对象 $stmt = $this->pdo->prepare("SELECT `staff_id`,`name`,`age`,`salary` FROM {$table} LIMIT :num"); //执行查询 $stmt->bindValue(':num', $num, \PDO::PARAM_INT); $stmt->execute(); $this->result = $stmt->fetchAll(\PDO::FETCH_ASSOC); } }
运行实例 »
点击 "运行实例" 按钮查看在线实例
实例
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2018/9/10 * Time: 16:00 */ namespace MVC\view; class View { 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>Document</title> <style> table,th,td { border: 1px solid black; } table { border-collapse: collapse; /*折叠表格线*/ width: 600px; margin: 30px auto; text-align: center; padding: 5px; } table tr:first-child { background-color: lightgreen; } table caption { font-size: 1.5em; margin-bottom: 15px; } </style> </head> <body> <table> <tr> <th>ID</th> <th>姓名</th> <th>年龄</th> <th>工资</th> </tr>'; foreach ($data as $staff) { $table .= '<tr>'; $table .= '<td>'.$staff['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; } }
运行实例 »
点击 "运行实例" 按钮查看在线实例
实例
<?php require './controller/Controller.php'; use mvc\controller\Controller; $controller = new Controller; $controller->index();
运行实例 »
点击 "运行实例" 按钮查看在线实例
MVC的设计思想是什么
MVC的核心思想是将一个应用分成三个基本部分:Model(模型)、View(视图)和Controller(控制器),这三个部分以最少的耦合协同工作,从而提高应用的可扩展性及可维护性