B2Core: 300-line phpMVC architecture

Source: Internet
Author: User
B2Core: 300-line phpMVC architecture
B2Core is a lightweight php MVC framework. the 300-line code encapsulates common CRUD and other practical functions.
For the latest code, see the http://b2core.b24.cn, and welcome criticism and suggestions.

This section provides detailed comments on each part of the code.
The frontend request format is

Http: // domain/index. php/controller/method/param1/param2/
Or
Http: // domain/controller/method/param1/param2/

  1. /**
  2. * B2Core is a PHP-based MVC architecture initiated by Brant (brantx@gmail.com)
  3. * The core idea is to maximize the flexibility of php based on the MVC framework.
  4. * Vison 2.0 (20120515)
  5. **/
  6. Define ('version', '2. 0 ');
  7. // Load the configuration file: database, url routing, etc.
  8. Require (APP. 'config. php ');
  9. // Load if the database is configured
  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 wocould 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 route 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. // Obtain the parameters of each segment in the URL
  35. $ Uri = rtrim ($ uri ,'/');
  36. $ Seg = explode ('/', $ uri );
  37. $ Des_dir = $ dir = '';
  38. /* Load the schema file _ construct. php of all directories at the controller's upper level in sequence
  39. * The architecture file can contain the parent classes of all controllers in the current directory and the functions 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 the method in the controller based on the url. if the method does not exist, error 404 is 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 functions
  66. * Load ($ path, $ instantiate) can dynamically load objects, such as controllers, models, and library classes.
  67. * $ Path is the address of the class file relative to the app.
  68. * When the value of $ instantiate is False, only files are referenced and objects are not instantiated.
  69. * When $ instantiate is an array, the array content is 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 the 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. * $ Variables in the param array are passed to the template file.
  93. * $ Cache = TRUE is returned in the string format instead of the browser output result.
  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. // Obtain the url segment, 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 logs
  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 error 404
  126. Function show_404 () // Display error 404
  127. {
  128. Header ("HTTP/1.1 404 Not Found ");
  129. // Call the template v/404.php
  130. View ('V/123 ');
  131. Exit (1 );
  132. }
  133. /* B2Core system class */
  134. // Abstract controller class. it is recommended that all controllers be sub-classes of this class or such classes.
  135. Class c {
  136. Function index ()
  137. {
  138. Echo "created based on B2 v". VERSION ";
  139. }
  140. }
  141. // Database operations
  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 ('unusable: '. mysql_error ());
  155. }
  156. Mysql_query ('set names utf8', $ this-> link );
  157. }
  158. // Execute the query. if the result is an array, the array data is returned.
  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, cocould not query the database \ n ";
  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, which encapsulates the operations of the general CURD module. 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 data in array format to the database
  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 data entry
  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
  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 a data or
  241. * Get ($ postquery = '', $ cur = 1, $ psize = 30) multiple data entries
  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 _ get', $ 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. }

  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. );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.