Home>Article>Backend Development> PHP source code method to implement single entry MVC structure

PHP source code method to implement single entry MVC structure

不言
不言 Original
2018-07-04 14:43:10 2007browse

This article mainly introduces the method of implementing single-entry MVC structure in PHP source code. It has certain reference value. Now I share it with you. Friends in need can refer to it.

Main:

  1. MVC directory structure

  2. Database tool class production

  3. Create public model classes and public controller classes

--------------:-------------------------------------- blog ├─index.php 入口文件 ├─Model 模型 │ └─UserModel.class.php 用户模型类 ├─View 视图 │ └─login.html 登录表单页面 ├─Controller 控制器 │ └─UserController.class.php 用户控制器 ├─Frame 公共使用的类 │ ├─BaseModel.class.php 数据库连接类 │ ├─BaseController.class.php 控制器公共操作(设置编码,信息跳转) │ └─Db.class.php 数据库操作工具类 └─Public 静态公共文件(js,css,images) ├─js/ js文件 ├─css/ css样式文件 └─images img图片 -----------------------------------------------------------------

MVC directory structure

1) Preparation: Create branch

1 $ git checkout master2 $ git checkout -b "mvc-dbtools-base"

2) Create directory structure:

MVC Directory: Model/ Controller/ View/

Static resource directory: Public/

3) Create the project entry file [index.php]

Copy the encoding of the original login.php header(...)

  Introducing the created controller UserController and model UserModel

1  $a();

 4) Create controller UserController 【Controller/UserController.class.php】

1 checkLoginInfo($data); 29 30 //结果提示信息 31 if($result){ 32 exit('登录成功'); 33 } else { 34 echo "用户名或密码不正确!"; 35 header('refresh:3; url=?'); 36 } 37 } 38 }

5) Create user model class UserModel [Model/UserModel.class.php]

Implementation method: checkLoginInfo() Check user name and password


      

View user model class

6) Login view: [view/login.html]

Modification of the introduction path,

Modification of the form submission action: action=?a=dlogin

1  2  3  4  5 登录 6  7  8 
9 10

11

12

13

14

登录

15


16 17

18 19

20 21

22

23 24

25 26

27 28

29

30 31

32

33 34 35

36

37
38

39

40 41 46 47


Click to view the login view source code

Database connection operations are all in the model and can be extracted to create database operation tool classes

Database tool class production

Database connection, set encoding, select database

Implement singleton

Get one row of data getOneRow, get a single array getOneData, get multiple rows getAllRows, add, delete, modify exec

Automatically generate insert or update statements autoExecute()

[Frame/Db.class.php]

1 host = !empty($conf['host']) ? $conf['host'] : 'localhost'; 27 $this->user = !empty($conf['user']) ? $conf['user'] : 'root'; 28 $this->pwd = !empty($conf['pwd']) ? $conf['pwd'] : 'root'; 29 $this->port = !empty($conf['port']) ? $conf['port'] : '3306'; 30 $this->charset = !empty($conf['charset']) ? $conf['charset'] : 'utf8'; 31 $this->dbname = !empty($conf['dbname']) ? $conf['dbname'] : 'web'; 32 33 $this->connect(); 34 } 35 36 /** 37 * 连接数据库,设置编码,选库 38 * @access private 39 */ 40 private function connect() 41 { 42 $this->link = @ mysql_connect("{$this->host}:{$this->port}", "$this->user", "$this->pwd") or die('连接失败!'.mysql_error()); 43 $this->setCharset($this->charset); 44 $this->useDb($this->dbname); 45 } 46 /** 47 * 设置字符便 48 * @access public 49 * @param string $char 字符编码 50 */ 51 public function setCharset($char) 52 { 53 $this->query("set names $char"); 54 } 55 /** 56 * 选择数据库 57 * @access public 58 * @param string $dbname 数据库名称 59 */ 60 public function useDb($dbname) 61 { 62 $this->query("use $dbname"); 63 } 64 65 /** 66 * 执行sql语句 67 * @param string $sql sql语句 68 * @return mixed 69 */ 70 private function query($sql) 71 { 72 $result = mysql_query($sql, $this->link); 73 if(false === $result) { 74 echo "

sql执行失败!
"; 75 echo "
失败语句:".$sql; 76 echo "
错误代号".mysql_errno(); 77 echo "
错误提示: ".mysql_error()."

"; 78 exit(); 79 } 80 return $result; 81 } 82 83 /** 84 * 获取本类实例 85 * @access public 86 * @param array $conf 数据库连接信息 87 * @return object 本类的单例对象 88 */ 89 public static function getDb($conf) 90 { 91 if(false === (static::$instance instanceof static)){ 92 static::$instance = new static($conf); 93 } 94 return static::$instance; 95 } 96 /** 97 * 禁止克隆 98 */ 99 public function __clone() 100 { 101 102 } 103 /** 104 * 关闭数据库连接 105 * @access public 106 */ 107 public function closeDb() 108 { 109 mysql_close($this->link); 110 } 111 112 public function exec($sql) 113 { 114 $result = $this->query($sql); 115 return $this->affectedRows(); 116 117 } 118 /** 119 * 受影响的行数 120 * @return int 返回受影响的行数 121 */ 122 private function affectedRows() 123 { 124 return mysql_affected_rows($this->link); 125 } 126 127 /** 128 * 执行 “返回一行数据”的查询 129 * @param string $sql sql语句 130 * @return array 一维数组(一行) 131 */ 132 public function getOneRow($sql) 133 { 134 $result = $this->query($sql); 135 $data = mysql_fetch_assoc($result); 136 mysql_free_result($result); 137 return $data; 138 } 139 /** 140 * 执行 "返回多行数据" 的查询 141 * @param string $sql sql语句 142 * @return array 二维数组 143 */ 144 public function getAllRows($sql) 145 { 146 $result = $this->query($sql); 147 $data = array(); 148 while($row = mysql_fetch_assoc($result)){ 149 $data[] = $row; 150 } 151 mysql_free_result($result); 152 return $data; 153 } 154 /** 155 * 执行“获取一个数据”的查询 156 * @param string $sql sql语句 157 * @return mixed 标量数据值 158 */ 159 public function getOneData($sql) 160 { 161 $result = $this->query($sql); 162 $data = mysql_fetch_row($result); 163 mysql_free_result($result); 164 return $data[0]; 165 } 166 167 /** 168 * 上次insert时的自增长id值 169 * @return int insert时的id值 170 */ 171 public function getInsertId() 172 { 173 return mysql_insert_id($this->link); 174 } 175 176 /** 177 * 序列化时,对指定数据进行序列化 178 * @return array 指定进行序列化的数据 179 */ 180 public function __sleep() 181 { 182 return array('host', 'port', 'user', 'pass','charset', 'dbname'); 183 } 184 /** 185 * 反序列化时,使用相应数据连接数据库 186 */ 187 public function __wakeup() 188 { 189 $this->connect(); //连接数据库 190 } 191 /** 192 * 自动生成insert语句或update语句 193 * @param array $data insert或update的数据 194 * @param string $table 操作的数据表 195 * @param string $act 是update还是insert操作 196 * @param string $where where条件 如 id=2 如果是update必须加,否则不执行直接返回false 197 * @return bool 执行insert与update的结果 198 */ 199 public function autoExecute($data, $table, $act='insert', $where='') 200 { 201 if($act == 'insert') { 202 $sql = "insert into ".$table."("; 203 $sql .=implode(",", array_keys($data)); 204 $sql .= ") values ('"; 205 $sql .= implode("','", array_values($data)); 206 $sql .= "')"; 207 208 $res = $this->exec($sql); 209 return $this->getInsertId(); 210 211 } else if($act == 'update') { 212 if(!$where) { return false; } 213 $sql = 'update '.$table.' set '; 214 foreach ($data as $k => $v) { 215 $sql .= $k."='".$v."',"; 216 } 217 $sql = substr($sql, 0, -1); 218 $sql .= ' where '.$where; 219 220 return $this->exec($sql); 221 } else { 222 return false; 223 } 224 225 } 226 }

Click to view the tool class

Create public model classes and public controller classes

 1) Public model class [Frame/BaseModel.class.php] Get database operation tool class instance

1 'localhost', 19 'user'=>'root', 20 'pwd'=>'root', 21 'port'=>'3306', 22 'charset'=>'utf8', 23 'dbname'=>'web', 24 ); 25 $conf = empty($config)? $conf : array_merge($conf,$config); 26 $this->db = Db::getDb($conf); 27 } 28 }

 2) Public control Container class [Frame/BaseController]:

Unified coding

Prompt message jump

1 返回

页面将在{$time}秒之后跳转!!"; 28 header("refresh: $time; url=$url"); 29 exit("

$msg

"); 30 } 31 }

3) Introduce tool classes, basic models and basic controller classes into the entry file

 【index.php】

1  $a();

Click to view the entry file

 4) User model class optimization【Model/UserModel.class.php】

1 db->getOneRow($sql); 18 return $res['pwd'] == md5($data['pwd']) ? : false; 19 } 20 }

5) User controller login operation, jump prompt optimization

Use the public controller method msg()

1 。。。。。。。 2 /** 3 * 登录操作: 校验登录信息 4 */ 5 public function dlogin() 6 { 7 //接收登录信息 8 $data = array(); 9 $data['username'] = trim($_POST['username']); 10 $data['pwd'] = trim($_POST['pwd']); 11 12 //实例化模型,调用模型方法 13 $model = new UserModel(); 14 $result = $model->checkLoginInfo($data); 15 //跳转提示 16 if($result){ 17 $this->msg('登录成功!', '?a=index',3); 18 } else { 19 $this->msg('用户名或密码不正确!!'); 20 } 21 }

Merge, save and push to git

1 $ git add -A 2 $ git commit -m "MVC结构,数据库操作类,基础模型类和基础控制器类制作" 3 $ git checkout master 4 $ git merge mvc-dbtools-base 5 $ git push origin master

Summary: Optimize the directory structure, create database operation classes, use basic model classes and basic controller classes

Next step: Implement singletons in model classes, further optimize the directory structure, and differentiate platforms (such as frontend, backend)

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

A brief discussion on PHP source code five: About the creation of array array

A brief discussion on PHP source code one: explode and implode function

The above is the detailed content of PHP source code method to implement single entry MVC structure. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn