b2Core: 300 lines of php MVC architecture

WBOY
Release: 2016-07-25 09:07:02
Original
1170 people have browsed it
b2Core is a lightweight php MVC framework, with 300 lines of code encapsulating common CRUD and other practical functions.
Please see the latest version of the code http://b2core.b24.cn, welcome criticism and suggestions.

This page has detailed comments on each part of the code.
The format of the front-end request is

http://domain/index.php/controller/method/param1/param2/
or
http://domain/controller/method/param1/param2/
  1. /**
  2. * B2Core is an MVC architecture based on PHP initiated by Brant (brantx@gmail.com)
  3. * The core idea is to retain the flexibility of PHP to the maximum extent based on the MVC framework
  4. * Vison 2.0 (20120515)
  5. **/
  6. define('VERSION','2.0');
  7. // Load configuration files: database, url routing, etc.
  8. require(APP. 'config.php');
  9. //If the database is configured, load it
  10. if(isset($db_config)) $db = new db($db_config);
  11. // Get the requested address compatible with 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. // Remove Magic_Quotes
  17. if(get_magic_quotes_gpc()) // Maybe would be removed in php6
  18. {
  19. function stripslashes_deep($value)
  20. {
  21. $value = is_array($value) ? array_map('stripslashes_deep', $value) : (isset($value) ? stripslashes($value) : null);
  22. return $ value;
  23. }
  24. $_POST = stripslashes_deep($_POST);
  25. $_GET = stripslashes_deep($_GET);
  26. $_COOKIE = stripslashes_deep($_COOKIE);
  27. }
  28. // Execute the url routing configured in config.php
  29. foreach ($route_config as $key => $val)
  30. {
  31. $key = str_replace(':any', '([^/.]+)', str_replace(':num', '([0-9 ]+)', $key));
  32. if (preg_match('#^'.$key.'#', $uri))$uri = preg_replace('#^'.$key.'#', $val , $uri);
  33. }
  34. // Get the parameters of each segment in the URL
  35. $uri = rtrim($uri,'/');
  36. $seg = explode('/',$uri);
  37. $des_dir = $dir = '';
  38. /* Load the architecture file __construct.php of all directories above the controller in sequence
  39. * The architecture file can contain the parent classes of all controllers in the current directory, and the functions that need to be called
  40. */
  41. foreach($seg as $cur_dir)
  42. {
  43. $des_dir.=$cur_dir."/";
  44. if(is_file(APP.'c'.$des_dir.'__construct.php')) {
  45. require(APP .'c'.$des_dir.'__construct.php');
  46. $dir .=array_shift($seg).'/';
  47. }
  48. else {
  49. break;
  50. }
  51. }
  52. /* Call control based on url If the method in the container does not exist, a 404 error will be returned
  53. * Default request class home->index()
  54. */
  55. $dir = $dir ? $dir:'/';
  56. array_unshift($seg,NULL);
  57. $class = isset($seg[1])?$seg[1]:'home';
  58. $method = isset($seg[2])?$seg[2]:'index';
  59. if(! is_file(APP.'c'.$dir.$class.'.php'))show_404();
  60. require(APP.'c'.$dir.$class.'.php');
  61. if(!class_exists ($class))show_404();
  62. if(!method_exists($class,$method))show_404();
  63. $B2 = new $class();
  64. call_user_func_array(array(&$B2, $method), array_slice ($seg, 3));
  65. /* B2 system function
  66. * load($path,$instantiate) can dynamically load objects, such as controllers, models, library classes, etc.
  67. * $path is the relative app of class files The address
  68. * When $instantiate is False, only the file is referenced and the object is not instantiated
  69. * When $instantiate is an array, the array content will be passed to the object as a parameter
  70. */
  71. function &load($path, $instantiate = TRUE )
  72. {
  73. $param = FALSE;
  74. if(is_array($instantiate)) {
  75. $param = $instantiate;
  76. $instantiate = TRUE;
  77. }
  78. $file = explode('/',$path);
  79. $class_name = array_pop($file);
  80. $object_name = md5($path);
  81. static $objects = array();
  82. if (isset($objects[$object_name])) return $objects[$object_name];
  83. require( APP.$path.'.php');
  84. if ($instantiate == FALSE) $objects[$object_name] = TRUE;
  85. if($param)$objects[$object_name] = new $class_name($param);
  86. else $objects[$object_name] = new $class_name();
  87. return $objects[$object_name];
  88. }
  89. /* Call view file
  90. * function view($view,$param = array(),$cache = FALSE)
  91. * $view is the address of the template file relative to the app/v/ directory. The address should remove the .php file suffix
  92. * The variables in the $param array will be passed to the template file
  93. * When $cache = TRUE, it is not like browsing instead of returning the result in the form of string
  94. */
  95. function view($view,$param = array(),$cache = FALSE)
  96. {
  97. if(!empty($param))extract($param) ;
  98. ob_start();
  99. if(is_file(APP.$view.'.php')) {
  100. require APP.$view.'.php';
  101. }
  102. else {
  103. echo 'view '.$view.' desn't exsit';
  104. return false;
  105. }
  106. // Return the file data if requested
  107. if ($cache === TRUE)
  108. {
  109. $buffer = ob_get_contents();
  110. @ob_end_clean();
  111. return $ buffer;
  112. }
  113. }
  114. // Get the fragment of url, for example, the url is /abc/def/g/ seg(1) = abc
  115. function seg($i)
  116. {
  117. global $seg;
  118. return isset($ seg[$i])?$seg[$i]:false;
  119. }
  120. // Write log
  121. function write_log($level = 0 ,$content = 'none')
  122. {
  123. file_put_contents(APP.'log /'.$level.'-'.date('Y-m-d').'.log', $content , FILE_APPEND );
  124. }
  125. //Display 404 error
  126. function show_404() //Display 404 error
  127. {
  128. header("HTTP/1.1 404 Not Found");
  129. // Call template v/404.php
  130. view('v/404');
  131. exit(1);
  132. }
  133. /* B2Core system class*/
  134. // Abstract controller class, it is recommended that all controllers be based on this class or a subclass of this class
  135. class c {
  136. function index()
  137. {
  138. echo "Based on B2 v ".VERSION." Create";
  139. }
  140. }
  141. // Database operation class
  142. class db {
  143. var $link;
  144. var $last_query;
  145. function __construct($conf)
  146. {
  147. $this->link = mysql_connect($conf['host'],$conf['user'], $conf['password']);
  148. if (!$this->link) {
  149. die('Unable to connect: ' . mysql_error( ));
  150. return FALSE;
  151. }
  152. $db_selected = mysql_select_db($conf['default_db']);
  153. if (!$db_selected) {
  154. die('Unable to use: ' . mysql_error());
  155. }
  156. mysql_query ('set names utf8',$this->link);
  157. }
  158. //Execute query query, if the result is an array, return array data
  159. function query($query)
  160. {
  161. $ret = array() ;
  162. $this->last_query = $query;
  163. $result = mysql_query($query,$this->link);
  164. if (!$result) {
  165. echo "DB Error, could not query the databasen";
  166. echo 'MySQL Error: ' . mysql_error();
  167. echo 'Error Query: ' . $query;
  168. exit;
  169. }
  170. if($result == 1 )return TRUE;
  171. while($record = mysql_fetch_assoc($result ))
  172. {
  173. $ret[] = $record;
  174. }
  175. return $ret;
  176. }
  177. function insert_id() {return mysql_insert_id();}
  178. // Execute multiple SQL statements
  179. function muti_query($query )
  180. {
  181. $sq = explode(";n",$query);
  182. foreach($sq as $s){
  183. if(trim($s)!= '')$this->query($s );
  184. }
  185. }
  186. }
  187. // Module class encapsulates common CURD module operations. It is recommended that all modules inherit this class.
  188. class m {
  189. var $db;
  190. var $table;
  191. var $fields;
  192. var $key;
  193. function __construct()
  194. {
  195. global $db;
  196. $this->db = $db;
  197. $this ->key = 'id';
  198. }
  199. public function __call($name, $arg) {
  200. return call_user_func_array(array($this, $name), $arg);
  201. }
  202. // Insert into database Array format data
  203. function add($elem = FALSE)
  204. {
  205. $query_list = array();
  206. if(!$elem)$elem = $_POST;
  207. foreach($this->fields as $f) {
  208. if(isset($elem[$f])){
  209. $elem[$f] = addslashes($elem[$f]);
  210. $query_list[] = "`$f` = '$elem[$f] '";
  211. }
  212. }
  213. $this->db->query("insert into `$this->table` set ".implode(',',$query_list));
  214. return $this-> ;db->insert_id();
  215. }
  216. // Delete a certain piece of data
  217. function del($id)
  218. {
  219. $this->db->query("delete from `$this->table ` where ".$this->key."='$id'");
  220. }
  221. // Update data
  222. function update($id , $elem = FALSE)
  223. {
  224. $query_list = array();
  225. if(!$elem)$elem = $_POST;
  226. foreach($this->fields as $f) {
  227. if(isset($elem[$f])){
  228. $elem[$f] = addslashes ($elem[$f]);
  229. $query_list[] = "`$f` = '$elem[$f]'";
  230. }
  231. }
  232. $this->db->query("update ` $this->table` set ".implode(',',$query_list)." where ".$this->key." ='$id'" );
  233. }
  234. // Count quantity
  235. function count($where='')
  236. {
  237. $res = $this->db->query("select count(*) as a from `$this->table` where 1 $where");
  238. return $res[0]['a'];
  239. }
  240. /* get($id) to get one piece of data or
  241. * get($postquery = '',$cur = 1,$psize = 30) to get multiple pieces data
  242. */
  243. function get()
  244. {
  245. $args = func_get_args();
  246. if(is_numeric($args[0])) return $this->__call('get_one', $args);
  247. return $ this->__call('get_many', $args);
  248. }
  249. function get_one($id)
  250. {
  251. $id = is_numeric($id)?$id:0;
  252. $res = $this-> db->query("select * from `$this->table` where ".$this->key."='$id'");
  253. if(isset($res[0]))return $res[0];
  254. return false;
  255. }
  256. function get_many($postquery = '',$cur = 1,$psize = 30)
  257. {
  258. $cur = $cur > 0 ?$cur:1;
  259. $start = ($cur - 1) * $psize;
  260. $query = "select * from `$this->table` where 1 $postquery limit $start , $psize";
  261. return $this->db ->query($query);
  262. }
  263. }
Copy code
  1. // All configuration content can be maintained in this file
  2. error_reporting(E_ERROR);
  3. if(file_exists(APP.'config_user.php')) require(APP.'config_user.php') ;
  4. //Configure url routing
  5. $route_config = array(
  6. '/reg/'=>'/user/reg/',
  7. '/logout/'=>'/user/logout/',
  8. );
  9. define('BASE','/');
  10. /* The database is configured according to SAE by default*/
  11. $db_config = array(
  12. 'host'=>SAE_MYSQL_HOST_M.':'.SAE_MYSQL_PORT,
  13. 'user' =>SAE_MYSQL_USER,
  14. 'password'=>SAE_MYSQL_PASS,
  15. 'default_db'=>SAE_MYSQL_DB
  16. );
Copy code


source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!