Use native PHP syntax to render pages and provide widget functions.
- /**
- * Obtaining and setting configuration parameters supports batch definition
- * If $key is an associative array, the configuration will be written in the form of K-V
- * If $key is a numeric index array, the corresponding configuration array will be returned
- * @param string |array $key configuration variable
- * @param array|null $value configuration value
- * @return array|null
- */
- function C($key,$value=null){
- static $_config = array();
- $args = func_num_args();
- if( $args == 1){
- if(is_string($key)){ //If the incoming key is a string
- return isset($_config[$key])?$_config[$key]:null;
- }
- if(is_array($key)){
- if(array_keys($key) !== range(0, count($key) - 1)){ //If the incoming key is an associative array
- $_config = array_merge ($_config, $key);
- }else{
- $ret = array();
- foreach ($key as $k) {
- $ret[$k] = isset($_config[$k])?$_config [$k]:null;
- }
- return $ret;
- }
- }
- }else{
- if(is_string($key)){
- $_config[$key] = $value;
- }else{
- halt( 'The parameters passed in are incorrect');
- }
- }
- return null;
- }
- /**
- * Call Widget
- * @param string $name widget name
- * @param array $data Variable list passed to widget, key is variable name, value is variable value
- * @return void
- */
- function W($name, $data = array()){
- $fullName = $name. 'Widget';
- if(!class_exists($fullName)){
- halt('Widget '.$name.' does not exist');
- }
- $widget = new $fullName();
- $widget->invoke ($data);
- }
- /**
- * Terminate program execution
- * @param string $str Termination reason
- * @param bool $display Whether to display the call stack, not displayed by default
- * @return void
- */
- function halt($str, $display=false){
- Log::fatal($str.' debug_backtrace:'.var_export(debug_backtrace(), true ));
- header("Content-Type:text/html; charset=utf-8");
- if($display){
- echo "
";
- debug_print_backtrace();
- echo " pre>";
- }
- echo $str;
- exit;
- }
- /**
- * Get database instance
- * @return DB
- */
- function M(){
- $dbConf = C(array('DB_HOST','DB_PORT','DB_USER' ,'DB_PWD','DB_NAME','DB_CHARSET'));
- return DB::getInstance($dbConf);
- }
- /**
- * If the file exists, include it
- * @param string $path file path
- * @return void
- */
- function includeIfExist($path){
- if(file_exists( $path)){
- include $path;
- }
- }
- /**
- * General control category
- */
- class SinglePHP {
- /**
- * controller
- * @var string
- */
- private $c;
- /**
- * Action
- * @var string
- */
- private $a;
- /**
- * Singleton
- * @var SinglePHP
- */
- private static $_instance;
- /**
- * Constructor, initialization configuration
- * @param array $conf
- */
- private function __construct($conf){
- C($conf);
- }
- private function __clone(){}
- /**
- * Get singleton
- * @param array $conf
- * @return SinglePHP
- */
- public static function getInstance($conf){
- if(!(self::$_instance instanceof self)){
- self::$_instance = new self($ conf);
- }
- return self::$_instance;
- }
- /**
- * Run application instance
- * @access public
- * @return void
- */
- public function run(){
- if(C('USE_SESSION') == true){
- session_start();
- }
- C('APP_FULL_PATH', getcwd().'/'.C('APP_PATH').'/');
- includeIfExist( C('APP_FULL_PATH').'/common.php');
- $pathMod = C('PATH_MOD');
- $pathMod = empty($pathMod)?'NORMAL':$pathMod;
- spl_autoload_register(array('SinglePHP', 'autoload'));
- if(strcmp(strtoupper($pathMod) ,'NORMAL') === 0 || !isset($_SERVER['PATH_INFO'])){
- $this->c = isset($_GET['c'])?$_GET['c'] :'Index';
- $this->a = isset($_GET['a'])?$_GET['a']:'Index';
- }else{
- $pathInfo = isset($_SERVER[' PATH_INFO'])?$_SERVER['PATH_INFO']:'';
- $pathInfoArr = explode('/',trim($pathInfo,'/'));
- if(isset($pathInfoArr[0]) && $ pathInfoArr[0] !== ''){
- $this->c = $pathInfoArr[0];
- }else{
- $this->c = 'Index';
- }
- if(isset($pathInfoArr [1])){
- $this->a = $pathInfoArr[1];
- }else{
- $this->a = 'Index';
- }
- }
- if(!class_exists($this-> ;c.'Controller')){
- halt('Controller'.$this->c.'does not exist');
- }
- $controllerClass = $this->c.'Controller';
- $controller = new $controllerClass();
- if(!method_exists($controller, $this->a.'Action')){
- halt('method'.$this->a.'does not exist');
- }
- call_user_func(array($controller,$this->a.'Action'));
- }
- /**
- * Automatic loading function
- * @param string $class class name
- */
- public static function autoload($class){
- if(substr($class ,-10)=='Controller'){
- includeIfExist(C('APP_FULL_PATH').'/Controller/'.$class.'.class.php');
- }elseif(substr($class,-6) =='Widget'){
- includeIfExist(C('APP_FULL_PATH').'/Widget/'.$class.'.class.php');
- }else{
- includeIfExist(C('APP_FULL_PATH').'/Lib/'.$class.'.class.php');
- }
- }
- }
- /**
- * Controller class
- */
- class Controller {
- /**
- * View instance
- * @var View
- */
- private $_view;
- /**
- * Constructor, initialize view instance, call hook
- */
- public function __construct(){
- $this->_view = new View();
- $this->_init();
- }
- /**
- * Pre-hook
- */
- protected function _init(){}
- /**
- * Render the template and output
- * @param null|string $tpl template file path
- * The parameter is the relative path relative to App/View/file, does not include the suffix name, such as index/index
- * If the parameter is empty, then $controller/$action.php is used by default
- * If the parameter does not contain "/", $controller/$tpl is used by default
- * @return void
- */
- protected function display($tpl=''){
- if($tpl === ''){
- $trace = debug_backtrace();
- $controller = substr($trace[1]['class'], 0, -10);
- $action = substr($trace[1]['function'], 0 , -6);
- $tpl = $controller . '/' . $action;
- }elseif(strpos($tpl, '/') === false){
- $trace = debug_backtrace();
- $controller = substr($trace[1]['class'], 0, -10);
- $tpl = $controller . '/' . $tpl;
- }
- $this->_view->display($tpl);
- }
- /**
- * Set a template variable for the view engine
- * @param string $name The variable name to be used in the template
- * @param mixed $value The value corresponding to the variable name in the template
- * @return void
- */
- protected function assign($name,$value){
- $this->_view->assign($name,$value);
- }
- /**
- * Output the data to the browser in json format and stop executing the code
- * @param array $data The data to be output
- */
- protected function ajaxReturn($data){
- echo json_encode($data);
- exit;
- }
- /**
- * Redirect to the specified url
- * @param string $url The url to be redirected
- * @param void
- */
- protected function redirect($url){
- header("Location: $url");
- exit;
- }
- }
- /**
- * View class
- */
- class View {
- /**
- * View file directory
- * @var string
- */
- private $_tplDir;
- /**
- * View file path
- * @var string
- */
- private $_viewPath;
- /**
- * View variable list
- * @var array
- */
- private $_data = array();
- /**
- * Variable list for tplInclude
- * @var array
- */
- private static $tmpData;
- /**
- * @param string $tplDir
- */
- public function __construct($tplDir=''){
- if($tplDir == ''){
- $this->_tplDir = './'.C('APP_PATH').'/View/';
- }else{
- $this->_tplDir = $tplDir;
- }
- }
- /**
- * Set a template variable for the view engine
- * @param string $key The variable name to be used in the template
- * @param mixed $value The value corresponding to the variable name in the template
- * @return void
- */
- public function assign($key, $value) {
- $this->_data[$key] = $value;
- }
- /**
- * Render the template and output
- * @param null|string $tplFile Template file path, relative path to App/View/file, does not include suffix name, such as index/index
- * @return void
- */
- public function display($tplFile) {
- $this->_viewPath = $this->_tplDir . $tplFile . '.php';
- unset($tplFile);
- extract($this->_data);
- include $this->_viewPath;
- }
- /**
- * Used to include other templates in the template file
- * @param string $path The path relative to the View directory
- * @param array $data The variable list passed to the sub-template, key is the variable name, value is the variable value
- * @return void
- */
- public static function tplInclude($path, $data=array()){
- self::$tmpData = array(
- 'path' => C('APP_FULL_PATH') . '/View/' . $path . '.php',
- 'data' => $data,
- );
- unset($path);
- unset($data);
- extract(self::$tmpData['data']);
- include self::$tmpData['path'];
- }
- }
- /**
- * Widget class
- * When using it, you need to inherit this class, rewrite the invoke method, and call display in the invoke method
- */
- class Widget {
- /**
- * View instance
- * @var View
- */
- protected $_view;
- /**
- * Widget name
- * @var string
- */
- protected $_widgetName;
- /**
- * Constructor, initialize view instance
- */
- public function __construct(){
- $this->_widgetName = get_class($this);
- $dir = C('APP_FULL_PATH') . '/Widget/Tpl/';
- $this->_view = new View($dir);
- }
- /**
- * Processing logic
- * @param mixed $data parameter
- */
- public function invoke($data){}
- /**
- * Render template
- * @param string $tpl template path, if it is empty, use the class name as the template name
- */
- protected function display($tpl=''){
- if($tpl == ''){
- $tpl = $this->_widgetName;
- }
- $this->_view->display($tpl);
- }
- /**
- * Set a template variable for the view engine
- * @param string $name The variable name to be used in the template
- * @param mixed $value The value corresponding to the variable name in the template
- * @return void
- */
- protected function assign($name,$value){
- $this->_view->assign($name,$value);
- }
- }
- /**
- * Database operation class
- * Usage method:
- * DB::getInstance($conf)->query('select * from table');
- * where $conf is an associative array and needs to contain the following keys:
- * DB_HOST DB_USER DB_PWD DB_NAME
- * You can use DB_PORT and DB_CHARSET to specify the port and encoding. The default is 3306 and utf8
- */
- class DB {
- /**
- * Database link
- * @var resource
- */
- private $_db;
- /**
- * Save the last sql
- * @var string
- */
- private $_lastSql;
- /**
- * The number of rows affected by the last sql statement
- * @var int
- */
- private $_rows;
- /**
- * Error in the last sql execution
- * @var string
- */
- private $_error;
- /**
- * Instance array
- * @var array
- */
- private static $_instance = array();
- /**
- * Constructor
- * @param array $dbConf configuration array
- */
- private function __construct($dbConf){
- if(!isset($dbConf['DB_CHARSET'])){
- $dbConf['DB_CHARSET'] = 'utf8';
- }
- $this->_db = mysql_connect($dbConf['DB_HOST'].':'.$dbConf['DB_PORT'],$dbConf['DB_USER'],$dbConf['DB_PWD']);
- if($this->_db === false){
- halt(mysql_error());
- }
- $selectDb = mysql_select_db($dbConf['DB_NAME'],$this->_db);
- if($selectDb === false){
- halt(mysql_error());
- }
- mysql_set_charset($dbConf['DB_CHARSET']);
- }
- private function __clone(){}
- /**
- * Get DB class
- * @param array $dbConf configuration array
- * @return DB
- */
- static public function getInstance($dbConf){
- if(!isset($dbConf['DB_PORT'])){
- $dbConf['DB_PORT'] = '3306';
- }
- $key = $dbConf['DB_HOST'].':'.$dbConf['DB_PORT'];
- if(!isset(self::$_instance[$key]) || !(self::$_instance[$key] instanceof self)){
- self::$_instance[$key] = new self($dbConf);
- }
- return self::$_instance[$key];
- }
- /**
- * Escaped string
- * @param string $str The string to be escaped
- * @return string The escaped string
- */
- public function escape($str){
- return mysql_real_escape_string($str, $this->_db);
- }
- /**
- * Query, used for select statements
- * @param string $sql The sql to be queried
- * @return bool|array If the query succeeds, it returns the corresponding array, if it fails, it returns false
- */
- public function query($sql){
- $this->_rows = 0;
- $this->_error = '';
- $this->_lastSql = $sql;
- $this->logSql();
- $res = mysql_query($sql,$this->_db);
- if($res === false){
- $this->_error = mysql_error($this->_db);
- $this->logError();
- return false;
- }else{
- $this->_rows = mysql_num_rows($res);
- $result = array();
- if($this->_rows >0) {
- while($row = mysql_fetch_array($res, MYSQL_ASSOC)){
- $result[] = $row;
- }
- mysql_data_seek($res,0);
- }
- return $result;
- }
- }
- /**
- * Query, used for insert/update/delete statements
- * @param string $sql The sql to be queried
- * @return bool|int If the query succeeds, it returns the number of affected records, if it fails, it returns false
- */
- public function execute($sql) {
- $this->_rows = 0;
- $this->_error = '';
- $this->_lastSql = $sql;
- $this->logSql();
- $result = mysql_query($sql, $this->_db) ;
- if ( false === $result) {
- $this->_error = mysql_error($this->_db);
- $this->logError();
- return false;
- } else {
- $this->_rows = mysql_affected_rows($this->_db);
- return $this->_rows;
- }
- }
- /**
- * Get the number of records affected by the last query
- * @return int The number of records affected
- */
- public function getRows(){
- return $this->_rows;
- }
- /**
- * Get the auto-increment ID generated after the last insert
- * @return int Auto-increment ID
- */
- public function getInsertId() {
- return mysql_insert_id($this->_db);
- }
- /**
- * Get the sql of the last query
- * @return string sql
- */
- public function getLastSql(){
- return $this->_lastSql;
- }
- /**
- * Get the error information of the last query
- * @return string error information
- */
- public function getError(){
- return $this->_error;
- }
- /**
- * Record sql to file
- */
- private function logSql(){
- Log::sql($this->_lastSql);
- }
- /**
- * Record error log to file
- */
- private function logError(){
- $str = '[SQL ERR]'.$this->_error.' SQL:'.$this->_lastSql;
- Log::warn($str);
- }
- }
- /**
- * Log class
- * Usage method: Log::fatal('error msg');
- * The saving path is App/Log, stored by day
- * Fatal and warning will be recorded in the .log.wf file
- */
- class Log{
- /**
- * Logging, supports SAE environment
- * @param string $msg Log content
- * @param string $level Log level
- * @param bool $wf Whether it is an error log
- */
- public static function write($msg, $level='DEBUG', $wf=false){
- if(function_exists('sae_debug')){ //如果是SAE,则使用sae_debug函数打日志
- $msg = "[{$level}]".$msg;
- sae_set_display_errors(false);
- sae_debug(trim($msg));
- sae_set_display_errors(true);
- }else{
- $msg = date('[ Y-m-d H:i:s ]')."[{$level}]".$msg."rn";
- $logPath = C('APP_FULL_PATH').'/Log/'.date('Ymd').'.log';
- if($wf){
- $logPath .= '.wf';
- }
- file_put_contents($logPath, $msg, FILE_APPEND);
- }
- }
- /**
- * Print fatal log
- * @param string $msg Log information
- */
- public static function fatal($msg){
- self::write($msg, 'FATAL', true);
- }
- /**
- * Print warning log
- * @param string $msg Log information
- */
- public static function warn($msg){
- self::write($msg, 'WARN', true);
- }
- /**
- * Print notice log
- * @param string $msg Log information
- */
- public static function notice($msg){
- self::write($msg, 'NOTICE');
- }
- /**
- * Print debug log
- * @param string $msg Log information
- */
- public static function debug($msg){
- self::write($msg, 'DEBUG');
- }
- /**
- * Print sql log
- * @param string $msg Log information
- */
- public static function sql($msg){
- self::write($msg, 'SQL');
- }
- }
- /**
- * ExtException class, records additional exception information
- */
- class ExtException extends Exception{
- /**
- * @var array
- */
- protected $extra;
- /**
- * @param string $message
- * @param array $extra
- * @param int $code
- * @param null $previous
- */
- public function __construct($message = "", $extra = array(), $code = 0, $previous = null){
- $this->extra = $extra;
- parent::__construct($message, $code, $previous);
- }
- /**
- * Get additional exception information
- * @return array
- */
- public function getExtra(){
- return $this->extra;
- }
- }
复制代码
|