Home Backend Development PHP Tutorial b2Core: 300 lines of php MVC architecture

b2Core: 300 lines of php MVC architecture

Jul 25, 2016 am 09:07 AM

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 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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles