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/
- /**
- * B2Core is an MVC architecture based on PHP initiated by Brant (brantx@gmail.com)
- * The core idea is to retain the flexibility of PHP to the maximum extent based on the MVC framework
- * Vison 2.0 (20120515)
- **/
-
- define('VERSION','2.0');
- // Load configuration files: database, url routing, etc.
- require(APP. 'config.php');
- //If the database is configured, load it
- 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 would 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 routing 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);
- }
-
- // Get the parameters of each segment in the URL
- $uri = rtrim($uri,'/');
- $seg = explode('/',$uri);
- $des_dir = $dir = '';
-
- /* Load the architecture file __construct.php of all directories above the controller in sequence
- * The architecture file can contain the parent classes of all controllers in the current directory, and the functions that need 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 control based on url If the method in the container does not exist, a 404 error will be 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 function
- * load($path,$instantiate) can dynamically load objects, such as controllers, models, library classes, etc.
- * $path is the relative app of class files The address
- * When $instantiate is False, only the file is referenced and the object is not instantiated
- * When $instantiate is an array, the array content will be 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 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
- * The variables in the $param array will be passed to the template file
- * When $cache = TRUE, it is not like browsing instead of returning the result in the form of string
- */
- 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;
- }
- }
-
- // Get the fragment of url, for example, the url is /abc/def/g/ seg(1) = abc
- function seg($i)
- {
- global $seg;
- return isset($ seg[$i])?$seg[$i]:false;
- }
-
- // Write log
- function write_log($level = 0 ,$content = 'none')
- {
- file_put_contents(APP.'log /'.$level.'-'.date('Y-m-d').'.log', $content , FILE_APPEND );
- }
-
- //Display 404 error
- function show_404() //Display 404 error
- {
- header("HTTP/1.1 404 Not Found");
- // Call template v/404.php
- view('v/404');
- exit(1);
- }
-
- /* B2Core system class*/
- // Abstract controller class, it is recommended that all controllers be based on this class or a subclass of this class
- class c {
- function index()
- {
- echo "Based on B2 v ".VERSION." Create";
- }
- }
-
- // Database operation class
- 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('Unable to use: ' . mysql_error());
- }
- mysql_query ('set names utf8',$this->link);
- }
-
- //Execute query query, if the result is an array, return array data
- function query($query)
- {
- $ret = array() ;
- $this->last_query = $query;
- $result = mysql_query($query,$this->link);
- if (!$result) {
- echo "DB Error, could not query the databasen";
- 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 encapsulates common CURD module operations. 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 into database Array format data
- 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 certain piece of data
- 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 quantity
- 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 one piece of data or
- * get($postquery = '',$cur = 1,$psize = 30) to get multiple pieces data
- */
- function get()
- {
- $args = func_get_args();
- if(is_numeric($args[0])) return $this->__call('get_one', $args);
- return $ this->__call('get_many', $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);
- }
- }
-
Copy code
- // 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
- );
-
Copy code
|