b2Core 是一個輕量 php MVC 框架, 300 行程式碼封裝了常用 CRUD 等實用功能。
最新版代碼請見
http://b2core.b24.cn ,歡迎批評和建議。
本頁中對程式碼的各個部分做了詳盡的註解.
前台請求的格式為
http://domain/index.php/controller/method/param1/param2/
或
http://domain/controller/method/param1/param2/
-
/**
- * B2Core 是由Brant (brantx@gmail.com)發起的基於PHP的MVC架構
- * 核心思想是在採用MVC框架的基礎上最大限度的保留php的靈活性
- * Vison 2.0 (20120515)
- **/
-
- define('VERSION','2.0');
-
- / / 載入設定檔:資料庫、url路由等等
- require(APP.'config.php');
-
- // 如果設定了資料庫則載入
- if(isset($db_config )) $db = new db($db_config);
-
- // 取得要求的位址相容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'];
-
- // 去除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($_GET);
- $_COOKIE = stripslashes_deep(pdeep_deep); 🎜>
- // 執行config.php 中設定的url路由
- 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);
- }
-
- // 取得URL中每一段的參數
- $uri = rtrim($uri,'/');
- $seg = explode('/',$uri);
- $des_dir = $dir = '';
-
- /*依序載入控制器上級所有目錄的架構檔案__construct.php
- * 架構檔案可以包含目前目錄下的所有控制器的父類,和需要呼叫的函數
- */
-
- 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;
- }
- }
-
- /* 根據url 呼叫控制器中的方法,如果不存在回傳404 錯誤
- * 預設請求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_slice($seg , 3));
-
- /* B2 系統函數
- * load($path,$instantiate) 可以動態載入對象,如:控制器、Model、庫類別等
- * $path是類別文件相對app 的位址
- * $instantiate 為False 時,僅引用文件,不實例化物件
- * $instantiate 為陣列時,陣列內容會作為參數傳遞給物件
- */
- function &load($path, $instantiate = TRUE )
- {
- $param = FALSE;
- if(is_array($instantiate)) {
- $param = $instantiate;
- $ }
- $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];
- }
-
- /* 呼叫view 檔案
- * function view($view,$param = array (),$cache = FALSE)
- * $view 是模板檔案相對app/v/ 目錄的位址,位址應移除.php 檔案後綴
- * $param 陣列中的變數會傳遞給範本檔案
- * $cache = TRUE 時,不像瀏覽器輸出結果,而是以string 的形式return
- */
- 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;
- }
- }
-
- // 取得url 的片段,如url 是/abc/def/g/ seg(1) = abc
- function seg($i)
- {
- global $seg;
- return isset($seg[$i])?$seg[$i]:false;
- }
-
- // 寫入日誌
- function write_log( $level = 0 ,$content = 'none')
- {
- file_put_contents(APP.'log/'.$level.'-'.date('Y-m-d').'.log', $ content , FILE_APPEND );
- }
-
- // 顯示404錯誤
- function show_404() //顯示404 錯誤
- {
- header("HTTP/1.1 4044404 4044 40404 4040477 ;
- // 呼叫模板v/404.php
- view('v/404');
- exit(1);
- }
-
- /* B2Core 系統類*/
- // 抽象的控制器類,建議所有的控制器均基層此類或此類的子類
- class c {
- function index ()
- {
- echo "基於B2 v".VERSION." 建立";
- }
- }
-
- // 資料庫操作類別
- class db {
- var $link;
- var $last_query;
- function __construct($conf)
- {
- $this->link = mysql_connect($conf['host'],$conf['user'] , $conf['password']);
- if (!$this->link) {
- die('無法連接: ' . mysql_error());
- return FALSE;
- }
- $db_selected = mysql_select_db($conf['default_db']);
- if (!$db_selected) {
- die('無法使用: ' . mysql_error()); } ('set names utf8',$this->link);
- }
-
- //執行query 查詢,如果結果為數組,則傳回數組資料
- 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();}
-
- // 執行多條SQL 語句
- function muti_query(uncque)
- {
- $sq = explode(";n",$query);
- foreach($sq as $s){
- if(trim($s)!= '')$this ->query($s);
- }
- }
- }
-
- // 模組類,封裝了通用CURD模組操作,建議所有模組都繼承此類。
- 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);
- }
-
- // 插入陣列格式資料給資料庫
- function add($elem = FALSE)
- {🎜> 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();
- }
-
- // 刪除某一條資料
- function del($id)
- {
- $this->db->query( "delete from `$this->table` where ".$this->key."='$id'");
- }
-
- // 更新資料
- 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'" );
- }
-
- // 統計數量
- function count($where='')
- {
- $res = $this->db->query("select count(*) as a from `$this->table` where 1 $where");
- return $res[0][' a'];
- }
-
- /* get($id) 取得一條資料或
- * get($postquery = '',$cur = 1,$psize = 30) 取得多個資料
- */
- function get()
{ $args = func_get_args(); if(is_numeric($args[0])) return $this->__call('get_onecall('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); } }複製程式碼
-
// 所有設定內容都可以在這個檔案維護
- error_reporting(E_ERROR);
- if(file_exists(APP.'config_user.php ')) require(APP.'config_user.php');
- // 設定url路由
- $route_config = array(
- '/reg/'=>'/user/reg/',
- '/logout/'=>'/user/logout/',
- );
-
- define('BASE','/');
-
- /* 資料庫預設依照SAE進行設定*/
- $db_config = array(
- 'host'=>SAE_MYSQL_HOST_M.':'.SAE_MYSQL_PORT,
- 'user'=>SAE_MYSQL_USER,
- 'passMY'SQL=SAE_MYo'SQL > 'default_db'=>SAE_MYSQL_DB
- );
-
-
複製程式碼
|