b2Core : 300 行的php MVC 架構

WBOY
發布: 2016-07-25 09:07:02
原創
1169 人瀏覽過
b2Core 是一個輕量 php MVC 框架, 300 行程式碼封裝了常用 CRUD 等實用功能。
最新版代碼請見 http://b2core.b24.cn ,歡迎批評和建議。

本頁中對程式碼的各個部分做了詳盡的註解.
前台請求的格式為

http://domain/index.php/controller/method/param1/param2/

http://domain/controller/method/param1/param2/
  1. /**
  2. * B2Core 是由Brant (brantx@gmail.com)發起的基於PHP的MVC架構
  3. * 核心思想是在採用MVC框架的基礎上最大限度的保留php的靈活性
  4. * Vison 2.0 (20120515)
  5. **/
  6. define('VERSION','2.0');
  7. / / 載入設定檔:資料庫、url路由等等
  8. require(APP.'config.php');
  9. // 如果設定了資料庫則載入
  10. if(isset($db_config )) $db = new db($db_config);
  11. // 取得要求的位址相容SAE
  12. $uri = '';
  13. if(isset($_SERVER['PATH_INFO']) ) $uri = $_SERVER['PATH_INFO'];
  14. if(isset($_SERVER['ORIG_PATH_INFO'])) $uri = $_SERVER['ORIG_PATH_INFO'];
  15. if(isset($_SERVER[' SCRIPT_URL'])) $uri = $_SERVER['SCRIPT_URL'];
  16. // 去除Magic_Quotes
  17. if(get_magic_quotes_gpc()) // Maybe would be removed in php6
  18. {🎜>{🎜> function stripslashes_deep($value)
  19. {
  20. $value = is_array($value) ? array_map('stripslashes_deep', $value) : (isset($value) ? stripslashes($value) : null); return $value;
  21. }
  22. $_POST = stripslashes_deep($_POST);
  23. $_GET = stripslashes_deep($_GET);
  24. $_COOKIE = stripslashes_deep($_GET);
  25. $_COOKIE = stripslashes_deep(pdeep_deep); 🎜>
  26. // 執行config.php 中設定的url路由
  27. foreach ($route_config as $key => $val)
  28. {
  29. $key = str_replace(':any', '( [^/.]+)', str_replace(':num', '([0-9]+)', $key));
  30. if (preg_match('#^'.$key.'#' , $uri))$uri = preg_replace('#^'.$key.'#', $val, $uri);
  31. }
  32. // 取得URL中每一段的參數
  33. $uri = rtrim($uri,'/');
  34. $seg = explode('/',$uri);
  35. $des_dir = $dir = '';
  36. /*依序載入控制器上級所有目錄的架構檔案__construct.php
  37. * 架構檔案可以包含目前目錄下的所有控制器的父類,和需要呼叫的函數
  38. */
  39. foreach($seg as $cur_dir)
  40. {
  41. $des_dir.=$cur_dir."/";
  42. if(is_file(APP.'c'.$des_dir.'__construct.php')) {
  43. require(APP.'c'.$des_dir.'__construct.php');
  44. $dir .=array_shift($seg).'/';
  45. }
  46. else {
  47. break;
  48. }
  49. }
  50. /* 根據url 呼叫控制器中的方法,如果不存在回傳404 錯誤
  51. * 預設請求class home->index()
  52. * /
  53. $dir = $dir ? $dir:'/';
  54. array_unshift($seg,NULL);
  55. $class = isset($seg[1])?$seg[1 ]:'home';
  56. $method = isset($seg[2])?$seg[2]:'index';
  57. if(!is_file(APP.'c'.$dir.$class .'.php'))show_404();
  58. require(APP.'c'.$dir.$class.'.php');
  59. if(!class_exists($class))show_404();
  60. if(!method_exists($class,$method))show_404();
  61. $B2 = new $class();
  62. call_user_func_array(array(&$B2, $method), array_slice($seg_slice($seg , 3));
  63. /* B2 系統函數
  64. * load($path,$instantiate) 可以動態載入對象,如:控制器、Model、庫類別等
  65. * $path是類別文件相對app 的位址
  66. * $instantiate 為False 時,僅引用文件,不實例化物件
  67. * $instantiate 為陣列時,陣列內容會作為參數傳遞給物件
  68. */
  69. function &load($path, $instantiate = TRUE )
  70. {
  71. $param = FALSE;
  72. if(is_array($instantiate)) {
  73. $param = $instantiate;
  74. $ }
  75. $file = explode('/',$path);
  76. $class_name = array_pop($file);
  77. $object_name = md5($path);
  78. static $objects = array();
  79. if (isset($objects[$object_name])) return $objects[$object_name];
  80. require(APP.$path.'.php');
  81. if ($instantiate == FALSE) $objects[$object_name] = TRUE;
  82. if($param)$objects[$object_name] = new $class_name($param);
  83. else $objects[ $object_name] = new $class_name();
  84. return $objects[$object_name];
  85. }
  86. /* 呼叫view 檔案
  87. * function view($view,$param = array (),$cache = FALSE)
  88. * $view 是模板檔案相對app/v/ 目錄的位址,位址應移除.php 檔案後綴
  89. * $param 陣列中的變數會傳遞給範本檔案
  90. * $cache = TRUE 時,不像瀏覽器輸出結果,而是以string 的形式return
  91. */
  92. function view($view,$param = array(),$cache = FALSE)
  93. {
  94. if(!empty($param))extract($param);
  95. ob_start();
  96. if(is_file(APP.$view.'.php')) {
  97. require APP.$view.'.php';
  98. }
  99. else {
  100. echo 'view '.$view.' desn't exsit';
  101. return false;
  102. }
  103. // Return the file data if requested
  104. if ($cache === TRUE)
  105. {
  106. $buffer = ob_get_contents();
  107. @ob_end_clean();
  108. return $buffer;
  109. }
  110. }
  111. // 取得url 的片段,如url 是/abc/def/g/ seg(1) = abc
  112. function seg($i)
  113. {
  114. global $seg;
  115. return isset($seg[$i])?$seg[$i]:false;
  116. }
  117. // 寫入日誌
  118. function write_log( $level = 0 ,$content = 'none')
  119. {
  120. file_put_contents(APP.'log/'.$level.'-'.date('Y-m-d').'.log', $ content , FILE_APPEND );
  121. }
  122. // 顯示404錯誤
  123. function show_404() //顯示404 錯誤
  124. {
  125. header("HTTP/1.1 4044404 4044 40404 4040477 ;
  126. // 呼叫模板v/404.php
  127. view('v/404');
  128. exit(1);
  129. }
  130. /* B2Core 系統類*/
  131. // 抽象的控制器類,建議所有的控制器均基層此類或此類的子類
  132. class c {
  133. function index ()
  134. {
  135. echo "基於B2 v".VERSION." 建立";
  136. }
  137. }
  138. // 資料庫操作類別
  139. class db {
  140. var $link;
  141. var $last_query;
  142. function __construct($conf)
  143. {
  144. $this->link = mysql_connect($conf['host'],$conf['user'] , $conf['password']);
  145. if (!$this->link) {
  146. die('無法連接: ' . mysql_error());
  147. return FALSE;
  148. }
  149. $db_selected = mysql_select_db($conf['default_db']);
  150. if (!$db_selected) {
  151. die('無法使用: ' . mysql_error()); } ('set names utf8',$this->link);
  152. }
  153. //執行query 查詢,如果結果為數組,則傳回數組資料
  154. function query($query)
  155. {
  156. $ret = array();
  157. $this->last_query = $query;
  158. $result = mysql_query($query,$this->link);
  159. if (!$result ) {
  160. echo "DB Error, could not query the databasen";
  161. echo 'MySQL Error: ' . mysql_error();
  162. echo 'Error Query: ' . $query;
  163. exit;
  164. }
  165. if($result == 1 )return TRUE;
  166. while($record = mysql_fetch_assoc($result))
  167. {
  168. $ret[] = $record;
  169. }
  170. }
  171. }
  172. }
  173. }
  174. }
  175. }
  176. }
  177. }
  178. }
  179. }
  180. }
  181. }
  182. }
  183. }
  184. }
  185. }
  186. }
  187. }
  188. }
  189. }
  190. }
  191. }
  192. }
  193. }
  194. return $ret;
  195. }
  196. function insert_id() {return mysql_insert_id();}
  197. // 執行多條SQL 語句
  198. function muti_query(uncque)
  199. {
  200. $sq = explode(";n",$query);
  201. foreach($sq as $s){
  202. if(trim($s)!= '')$this ->query($s);
  203. }
  204. }
  205. }
  206. // 模組類,封裝了通用CURD模組操作,建議所有模組都繼承此類。
  207. class m {
  208. var $db;
  209. var $table;
  210. var $fields;
  211. var $key;
  212. function __construct()
  213. {
  214. global $ db;
  215. $this->db = $db;
  216. $this->key = 'id';
  217. }
  218. public function __call($name, $arg) {
  219. return call_user_func_array(array($this, $name), $arg);
  220. }
  221. // 插入陣列格式資料給資料庫
  222. function add($elem = FALSE)
  223. {🎜> function add($elem = FALSE)
  224. {
  225. $query_list = array();
  226. if(!$elem)$elem = $_POST;
  227. foreach($this->fields as $f) {
  228. if(isset($elem[ $f])){
  229. $elem[$f] = addslashes($elem[$f]);
  230. $query_list[] = "`$f` = '$elem[$f]'";
  231. }
  232. }
  233. $this->db->query("insert into `$this->table` set ".implode(',',$query_list));
  234. return $this ->db->insert_id();
  235. }
  236. // 刪除某一條資料
  237. function del($id)
  238. {
  239. $this->db->query( "delete from `$this->table` where ".$this->key."='$id'");
  240. }
  241. // 更新資料
  242. function update($id , $elem = FALSE)
  243. {
  244. $query_list = array();
  245. if(!$elem)$elem = $_POST;
  246. foreach($this->fields as $f) {
  247. if(isset($elem[$f])){
  248. $elem[$f] = addslashes($elem[$f]);
  249. $query_list[] = "`$f` = '$elem[$f]'";
  250. }
  251. }
  252. $this->db->query("update `$this->table` set ".implode(',',$query_list )." where ".$this->key." ='$id'" )​​;
  253. }
  254. // 統計數量
  255. function count($where='')
  256. {
  257. $res = $this->db->query("select count(*) as a from `$this->table` where 1 $where");
  258. return $res[0][' a'];
  259. }
  260. /* get($id) 取得一條資料或
  261. * get($postquery = '',$cur = 1,$psize = 30) 取得多個資料
  262. */
  263. function get()
{
$args = func_get_args(); if(is_numeric($args[0])) return $this->__call('get_onecall('get_one ', $args); return $this->__call('get_many', $args);
} function get_one($id) { $id = is_numeric($id)?$id:0; $res = $this->db->query("select * from `$this->table` where ".$this->key."='$ id'"); if(isset($res[0]))return $res[0]; return false; } function get_many($postquery = '' ,$cur = 1,$psize = 30) { $cur = $cur > 0 ?$cur:1; $start = ($cur - 1) * $psize; $query = "select * from `$this->table` where 1 $postquery limit $start , $psize"; return $this->db->query($query); } }複製程式碼
  1. // 所有設定內容都可以在這個檔案維護
  2. error_reporting(E_ERROR);
  3. if(file_exists(APP.'config_user.php ')) require(APP.'config_user.php');
  4. // 設定url路由
  5. $route_config = array(
  6. '/reg/'=>'/user/reg/',
  7. '/logout/'=>'/user/logout/',
  8. );
  9. define('BASE','/');
  10. /* 資料庫預設依照SAE進行設定*/
  11. $db_config = array(
  12. 'host'=>SAE_MYSQL_HOST_M.':'.SAE_MYSQL_PORT,
  13. 'user'=>SAE_MYSQL_USER,
  14. 'passMY'SQL=SAE_MYo'SQL > 'default_db'=>SAE_MYSQL_DB
  15. );
複製程式碼

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!