search
HomeBackend DevelopmentPHP Tutorialb2Core: 300 lines of php MVC architecture

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


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
How to calculate the total number of elements in a PHP multidimensional array?How to calculate the total number of elements in a PHP multidimensional array?May 15, 2025 pm 09:00 PM

Calculating the total number of elements in a PHP multidimensional array can be done using recursive or iterative methods. 1. The recursive method counts by traversing the array and recursively processing nested arrays. 2. The iterative method uses the stack to simulate recursion to avoid depth problems. 3. The array_walk_recursive function can also be implemented, but it requires manual counting.

What are the characteristics of do-while loops in PHP?What are the characteristics of do-while loops in PHP?May 15, 2025 pm 08:57 PM

In PHP, the characteristic of a do-while loop is to ensure that the loop body is executed at least once, and then decide whether to continue the loop based on the conditions. 1) It executes the loop body before conditional checking, suitable for scenarios where operations need to be performed at least once, such as user input verification and menu systems. 2) However, the syntax of the do-while loop can cause confusion among newbies and may add unnecessary performance overhead.

How to hash strings in PHP?How to hash strings in PHP?May 15, 2025 pm 08:54 PM

Efficient hashing strings in PHP can use the following methods: 1. Use the md5 function for fast hashing, but is not suitable for password storage. 2. Use the sha256 function to improve security. 3. Use the password_hash function to process passwords to provide the highest security and convenience.

How to implement array sliding window in PHP?How to implement array sliding window in PHP?May 15, 2025 pm 08:51 PM

Implementing an array sliding window in PHP can be done by functions slideWindow and slideWindowAverage. 1. Use the slideWindow function to split an array into a fixed-size subarray. 2. Use the slideWindowAverage function to calculate the average value in each window. 3. For real-time data streams, asynchronous processing and outlier detection can be used using ReactPHP.

How to use the __clone method in PHP?How to use the __clone method in PHP?May 15, 2025 pm 08:48 PM

The __clone method in PHP is used to perform custom operations when object cloning. When cloning an object using the clone keyword, if the object has a __clone method, the method will be automatically called, allowing customized processing during the cloning process, such as resetting the reference type attribute to ensure the independence of the cloned object.

How to use goto statements in PHP?How to use goto statements in PHP?May 15, 2025 pm 08:45 PM

In PHP, goto statements are used to unconditionally jump to specific tags in the program. 1) It can simplify the processing of complex nested loops or conditional statements, but 2) Using goto may make the code difficult to understand and maintain, and 3) It is recommended to give priority to the use of structured control statements. Overall, goto should be used with caution and best practices are followed to ensure the readability and maintainability of the code.

How to implement data statistics in PHP?How to implement data statistics in PHP?May 15, 2025 pm 08:42 PM

In PHP, data statistics can be achieved by using built-in functions, custom functions, and third-party libraries. 1) Use built-in functions such as array_sum() and count() to perform basic statistics. 2) Write custom functions to calculate complex statistics such as medians. 3) Use the PHP-ML library to perform advanced statistical analysis. Through these methods, data statistics can be performed efficiently.

How to use anonymous functions in PHP?How to use anonymous functions in PHP?May 15, 2025 pm 08:39 PM

Yes, anonymous functions in PHP refer to functions without names. They can be passed as parameters to other functions and as return values ​​of functions, making the code more flexible and efficient. When using anonymous functions, you need to pay attention to scope and performance issues.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment