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/
- /**
- * B2Core is a PHP-based MVC architecture initiated by Brant (brantx@gmail.com)
- * The core idea is to maximize the flexibility of php based on the MVC framework.
- * Vison 2.0 (20120515)
- **/
-
- Define ('version', '2. 0 ');
- // Load the configuration file: database, url routing, etc.
- Require (APP. 'config. php ');
- // Load if the database is configured
- If (isset ($ db_config) $ db = new db ($ db_config );
- // Get the requested address compatible with SAE
- $ Uri = '';
- If (isset ($ _ SERVER ['path _ info']) $ uri = $ _ SERVER ['path _ info'];
- If (isset ($ _ SERVER ['orig _ PATH_INFO ']) $ uri = $ _ SERVER ['orig _ PATH_INFO'];
- If (isset ($ _ SERVER ['script _ url']) $ uri = $ _ SERVER ['script _ url'];
- // Remove Magic_Quotes
- If (get_magic_quotes_gpc () // Maybe wocould be removed in php6
- {
- Function stripslashes_deep ($ value)
- {
- $ Value = is_array ($ value )? Array_map ('stripslashes _ deep ', $ value): (isset ($ value )? Stripslashes ($ value): null );
- Return $ value;
- }
- $ _ POST = stripslashes_deep ($ _ POST );
- $ _ GET = stripslashes_deep ($ _ GET );
- $ _ COOKIE = stripslashes_deep ($ _ COOKIE );
- }
- // Execute the url route configured in config. php
- Foreach ($ route_config as $ key => $ val)
- {
- $ Key = str_replace (': any',' ([^ \/.] +) ', str_replace (': num', '([0-9] +)', $ key ));
- If (preg_match ('# ^ '. $ key. '#', $ uri) $ uri = preg_replace ('# ^ '. $ key. '#', $ val, $ uri );
- }
- // Obtain the parameters of each segment in the URL
- $ Uri = rtrim ($ uri ,'/');
- $ Seg = explode ('/', $ uri );
- $ Des_dir = $ dir = '';
- /* Load the schema file _ construct. php of all directories at the controller's upper level in sequence
- * The architecture file can contain the parent classes of all controllers in the current directory and the functions to be called.
- */
- Foreach ($ seg as $ cur_dir)
- {
- $ Des_dir. = $ cur_dir ."/";
- If (is_file (APP. 'c'. $ des_dir. '_ construct. php ')){
- Require (APP. 'c'. $ des_dir. '_ construct. php ');
- $ Dir. = array_shift ($ seg ).'/';
- }
- Else {
- Break;
- }
- }
- /* Call the method in the controller based on the url. if the method does not exist, error 404 is returned.
- * Default request class home-> index ()
- */
- $ Dir = $ dir? $ Dir :'/';
- Array_unshift ($ seg, NULL );
- $ Class = isset ($ seg [1])? $ Seg [1]: 'home ';
- $ Method = isset ($ seg [2])? $ Seg [2]: 'index ';
- If (! Is_file (APP. 'c'. $ dir. $ class. '. php') show_404 ();
- Require (APP. 'c'. $ dir. $ class. '. php ');
- If (! Class_exists ($ class) show_404 ();
- If (! Method_exists ($ class, $ method) show_404 ();
- $ B2 = new $ class ();
- Call_user_func_array (array (& $ B2, $ method), array_slice ($ seg, 3 ));
- /* B2 system functions
- * Load ($ path, $ instantiate) can dynamically load objects, such as controllers, models, and library classes.
- * $ Path is the address of the class file relative to the app.
- * When the value of $ instantiate is False, only files are referenced and objects are not instantiated.
- * When $ instantiate is an array, the array content is passed to the object as a parameter.
- */
- Function & load ($ path, $ instantiate = TRUE)
- {
- $ Param = FALSE;
- If (is_array ($ instantiate )){
- $ Param = $ instantiate;
- $ Instantiate = TRUE;
- }
- $ File = explode ('/', $ path );
- $ Class_name = array_pop ($ file );
- $ Object_name = md5 ($ path );
-
- Static $ objects = array ();
- If (isset ($ objects [$ object_name]) return $ objects [$ object_name];
- Require (APP. $ path. '. php ');
- If ($ instantiate = FALSE) $ objects [$ object_name] = TRUE;
- If ($ param) $ objects [$ object_name] = new $ class_name ($ param );
- Else $ objects [$ object_name] = new $ class_name ();
- Return $ objects [$ object_name];
- }
- /* Call the view File
- * Function view ($ view, $ param = array (), $ cache = FALSE)
- * $ View is the address of the template file relative to the app/v/Directory. the address should remove the. php file suffix.
- * $ Variables in the param array are passed to the template file.
- * $ Cache = TRUE is returned in the string format instead of the browser output result.
- */
- Function view ($ view, $ param = array (), $ cache = FALSE)
- {
- If (! Empty ($ param) extract ($ param );
- Ob_start ();
- If (is_file (APP. $ view. '. php ')){
- Require APP. $ view. '. php ';
- }
- Else {
- Echo 'view'. $ view. 'desn \'t exsit ';
- Return false;
- }
- // Return the file data if requested
- If ($ cache = TRUE)
- {
- $ Buffer = ob_get_contents ();
- @ Ob_end_clean ();
- Return $ buffer;
- }
- }
- // Obtain the url segment, for example, the url is/abc/def/g/seg (1) = abc
- Function seg ($ I)
- {
- Global $ seg;
- Return isset ($ seg [$ I])? $ Seg [$ I]: false;
- }
- // Write logs
- Function write_log ($ level = 0, $ content = 'none ')
- {
- File_put_contents (APP. 'Log/'. $ level.'-'. date ('Y-m-D').'. log', $ content, FILE_APPEND );
- }
- // Display error 404
- Function show_404 () // Display error 404
- {
- Header ("HTTP/1.1 404 Not Found ");
- // Call the template v/404.php
- View ('V/123 ');
- Exit (1 );
- }
- /* B2Core system class */
- // Abstract controller class. it is recommended that all controllers be sub-classes of this class or such classes.
- Class c {
- Function index ()
- {
- Echo "created based on B2 v". VERSION ";
- }
- }
- // Database operations
- Class db {
- Var $ link;
- Var $ last_query;
- Function _ construct ($ conf)
- {
- $ This-> link = mysql_connect ($ conf ['host'], $ conf ['user'], $ conf ['password']);
- If (! $ This-> link ){
- Die ('unable to connect: '. mysql_error ());
- Return FALSE;
- }
- $ Db_selected = mysql_select_db ($ conf ['default _ db']);
- If (! $ Db_selected ){
- Die ('unusable: '. mysql_error ());
- }
- Mysql_query ('set names utf8', $ this-> link );
- }
- // Execute the query. if the result is an array, the array data is returned.
- Function query ($ query)
- {
- $ Ret = array ();
- $ This-> last_query = $ query;
- $ Result = mysql_query ($ query, $ this-> link );
- If (! $ Result ){
- Echo "DB Error, cocould not query the database \ n ";
- Echo 'MySQL Error: '. mysql_error ();
- Echo 'error Query: '. $ query;
- Exit;
- }
- If ($ result = 1) return TRUE;
- While ($ record = mysql_fetch_assoc ($ result ))
- {
- $ Ret [] = $ record;
- }
- Return $ ret;
- }
- Function insert_id () {return mysql_insert_id ();}
-
- // Execute multiple SQL statements
- Function muti_query ($ query)
- {
- $ Sq = explode ("; \ n", $ query );
- Foreach ($ sq as $ s ){
- If (trim ($ s )! = '') $ This-> query ($ s );
- }
- }
- }
- // Module class, which encapsulates the operations of the general CURD module. it is recommended that all modules inherit this class.
- Class m {
- Var $ db;
- Var $ table;
- Var $ fields;
- Var $ key;
- Function _ construct ()
- {
- Global $ db;
- $ This-> db = $ db;
- $ This-> key = 'id ';
- }
- Public function _ call ($ name, $ arg ){
- Return call_user_func_array (array ($ this, $ name), $ arg );
- }
- // Insert data in array format to the database
- Function add ($ elem = FALSE)
- {
- $ Query_list = array ();
- If (! $ Elem) $ elem =$ _ POST;
- Foreach ($ this-> fields as $ f ){
- If (isset ($ elem [$ f]) {
- $ Elem [$ f] = addslashes ($ elem [$ f]);
- $ Query_list [] = "'$ f' =' $ elem [$ f] '";
- }
- }
- $ This-> db-> query ("insert into '$ this-> table 'set". implode (', ', $ query_list ));
- Return $ this-> db-> insert_id ();
- }
- // Delete a data entry
- Function del ($ id)
- {
- $ This-> db-> query ("delete from '$ this-> table 'Where". $ this-> key. "=' $ ID '");
- }
- // Update data
- Function update ($ id, $ elem = FALSE)
- {
- $ Query_list = array ();
- If (! $ Elem) $ elem =$ _ POST;
- Foreach ($ this-> fields as $ f ){
- If (isset ($ elem [$ f]) {
- $ Elem [$ f] = addslashes ($ elem [$ f]);
- $ Query_list [] = "'$ f' =' $ elem [$ f] '";
- }
- }
- $ This-> db-> query ("update' $ this-> table 'set ". implode (',', $ query_list ). "where ". $ this-> key. "= '$ ID '");
- }
- // Count
- Function count ($ where = '')
- {
- $ Res = $ this-> db-> query ("select count (*) as a from '$ this-> table 'Where 1 $ where ");
- Return $ res [0] ['A'];
- }
- /* Get ($ id) to get a data or
- * Get ($ postquery = '', $ cur = 1, $ psize = 30) multiple data entries
- */
- Function get ()
- {
- $ Args = func_get_args ();
- If (is_numeric ($ args [0]) return $ this->__ call ('Get _ one', $ args );
- Return $ this->__ call ('Get _ get', $ 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 );
- }
- }
- // All configuration content can be maintained in this file
- Error_reporting (E_ERROR );
- If (file_exists (APP. 'config _ user. php') require (APP. 'config _ user. php ');
- // Configure url routing
- $ Route_config = array (
- '/Reg/' => '/user/reg /',
- '/Logout/' => '/user/logout /',
- );
- Define ('base ','/');
- /* The database is configured according to SAE by default */
- $ Db_config = array (
- 'Host' => SAE_MYSQL_HOST_M. ':'. SAE_MYSQL_PORT,
- 'User' => SAE_MYSQL_USER,
- 'Password' => SAE_MYSQL_PASS,
- 'Default _ db' => SAE_MYSQL_DB
- );
|