Exphp代码走读(二)

App.class.php

  1 <?php
  2 namespace System\Core;
  3 use System\Driver;
  4
  5 class App{
  6     public $DB;
  7     public $Cache;
  8     public $Session;
  9     public $Controller;
 10
 11     public function __construct(){
 12         DBUG ? set_error_handler(array($this,‘errorHandler‘)) : NULL;//DBUG模式,设置错误处理
 13         set_exception_handler(array($this,‘exceptionHandler‘));//注册异常处理函数
 14
 15         $appConfig = null;
 16
 17 /*
 18         $appConfig = apc_item(‘APP_CONFIG_‘.APP);
 19         if(empty($appConfig)){
 20             include APPDIR . ‘/Config/App.php‘;
 21             apc_item(‘APP_CONFIG_‘.APP,$appConfig);
 22         }
 23  */
 24         include APPDIR . ‘/Config/‘ . (APP == APPNAME ? ‘App‘:APP) . ‘.php‘;//加载配置文件
 25
 26         $isAjaxRequest = ( strtoupper(getsrv(‘HTTP_X_REQUESTED_WITH‘)) == ‘XMLHTTPREQUEST‘);//判断是否ajax请求
 27
 28         global_item($appConfig,true);//把$appConfig加载到函数的静态变量
 29         global_item(‘timestamp‘,getsrv(‘REQUEST_TIME‘));
 30         global_item(‘requestApp‘,APP);
 31         global_item(‘isAjaxRequest‘,$isAjaxRequest);
 32
 33         $this->DB = new Driver\MySQLi($appConfig[‘db‘]);
 34
 35         $this->Cache = new Driver\Memcached($appConfig[‘app_cache_persistent_id‘],$appConfig[‘app_cache_servers‘]);
 36
 37         $this->loadSiteConfig();
 38
 39         $this->Session = new Session($appConfig[‘app_session_provider‘]);
 40
 41     }
 42
 43     public function run(){
 44         $this->Session->__autoSession();//session启动
 45         $controller = $method = $params = null;
 46
 47        $path = parse_url($this->_getRequestUrl(),PHP_URL_PATH);//解析请求的URL,获取path部分
 48         extract($this->_route($path));//提取数组字段
 49
 50         header(‘Content-Type: text/html; charset=‘ . config_item(‘charset‘));
 51
 52         $controllerName = $controller;
 53         $methodName = $method.‘Method‘;
 54
 55         if(preg_match("/\W/",$method)){
 56        throw new \Exception($methodName,‘ does not allowed.‘, 404);
 57         }
 58
 59         if($controllerName == ‘do‘){
 60        return $this->_invokeBundleMethod($method,$params);
 61         }
 62         if(preg_match(‘/\W/‘,$controllerName)){
 63        throw \Exception($controllerName . ‘ does not allowed.‘,404);
 64         }
 65         $controllerClass = APPNS . ‘\\Controller\\‘ . ucfirst($controllerName);
 66
 67         $this->Controller = new $controllerClass;//实例化控制器类
 68         $this->Controller->setControllerParams($controllerName,$method);//将原始的controllername和method传给控制器类
 69
 70         if(!method_exists($this->Controller,$methodName)){
 71        throw new \Exception($controllerClass . ‘->‘ , $methodName . ‘ does not exists.‘, 404);
 72         }//方法不存在,抛出异常
 73         if(empty($params)){
 74        $this->Controller->$methodName();//无参数时直接运行函数
 75         }else{
 76        call_user_func_array(array($this->Controller,$methodName), $params);//用call_user_func_array运行带参数的请求
 77         }
 78     }
 79
 80     public function loadSiteConfig($isForceReload = false){
 81         $configFile = APPDIR . ‘/Config/Site.php‘;
 82
 83         if(file_exists($configFile)){
 84             include $configFile;
 85         }else{
 86             $tableName = global_item(‘app_config_table_name‘);
 87
 88             $params = array(‘indexField‘=>‘name‘,‘valueField‘=>‘value‘,‘pageSize‘=>1000);
 89             $siteConfig = $this->DB->getColumn($tableName,‘‘,$params);
 90
 91             $strData = ‘<?php‘."\r\n" . ‘$siteConfig = ‘ . var_export($siteConfig,true);
 92             file_put_contents($configFile,$strData);
 93         }
 94         config_item($siteConfig);
 95
 96         unset($siteConfig);
 97
 98         return $configFile;
 99     }
100
101
102     public function messageHandler($message,$url=‘‘,$second = 2,$template=‘show_message‘,$code=200){
103         $handler = $this->Controller;
104         if(!$handler){
105             $handler = new Controller();
106         }
107
108         $handler->showMessage($message,$url,$second,$template,$code);
109     }
110
111     public function exceptionHandler($exception){
112 $this->messageHandler($exception->getMessage(),‘‘,-1,‘show_message‘,$exception->getCode());
113     }
114
115     public function errorHandler($errno,$errstr,$errfile,$errline){
116         if(!(error_reporting() & $errno)){
117             return ;
118         }
119
120         switch($errno){
121         case E_USER_ERROR:
122             exit(1);
123         case E_USER_WARNING:
124             break;
125         case E_USER_NOTICE:
126             break;
127         default:
128 break;
129         }
130         return true;
131     }
132
133     public function shutdownHandler(){
134
135     }
136
137     public function _getRequestUrl(){
138         $requestUrl = ‘‘;
139         if(defined(‘STDIN‘)){
140             $args = array_slice(getsrv(‘argv‘),1);
141             if($args){
142                 foreach($args as $arg) {
143                     $requestUrl .= urlencode($arg) . ‘/‘;
144                 }
145                 $requestUrl = trim($requestUrl,‘/‘);
146             }
147         } else {
148             $requestUrl = getsrv(‘REQUEST_URI‘);
149         }
150         return $requestUrl;
151     }
152
153
154     private function _route($path){
155         $path = trim(preg_replace("/+",‘/‘,$path),‘/‘);
156
157         if(empty($path) || file_exists(RUNPATH . ‘/‘ . $path) || strstr($path,‘index.php‘)){
158 $x = array( isset($_GET[‘c‘]) ? trim(strip_tags($_GET[‘c‘])) : ‘main‘);
159         }elseif($path == ‘do‘ || $path == ‘load‘){
160             $x = array( isset($_GET[‘c‘]) ? trim(strip_tags($_GET[‘c‘]) : ‘do‘));
161         }else{
162             $routes = null;
163
164             include APPDIR . ‘/Config/Routes.php‘;
165
166             foreach($routes as $key => $val){
167                 if( strpos($key,‘(‘ === false ) {
168                     if($key == $path){
169                         $path = $val;
170                         break;
171                     }
172                 } else {
173                     $key = str_replac(array(‘:num‘,‘:any‘),array(‘\d+‘,‘.+‘),$key);
174
175                     if ( preg_match(‘#^‘ . $key . ‘$#‘ , $path) ) {
176                         $path = preg_replace(‘#^‘.$key.‘$#‘,$val,$path);
177                         break;
178                     }
179
180                 }
181             }
182
183             if(strpos($path,‘?‘) !== false) {
184                 $urls = parse_url($path);
185                 $path = $urls[‘path‘];
186                 if( !empty($urls[‘query‘])){
187                     $queries = array();
188                     parse_str($urls[‘query‘],$queries);
189                     $_GET += $queries;
190                 }
191             }
192
193             $x = explode(‘/‘, $path);
194         }
195         $_x = array();
196         $_x[‘controller‘] = empty($x[0]) ? ‘main‘ : trim($x[0]);
197         $_x[‘method‘] = empty($x[1]) ? ( isset($_GET[‘m‘]) ? trim (strip_tags($_GET[‘m‘])) : ‘index‘) : trim($x[1]);
198         $_x[‘params‘] = count($x) > 2 ? array_slice($x , 2) : ( isset($_GET[‘v‘]) ? array($_GET[‘v‘] : null );
199         return $_x;
200     }
201
202     private function _invokeBundleMethod($method,$params=NULL){
203         $fliter_arr = array(‘status‘,‘ping‘,‘userAgent‘,‘cacheStatus‘,‘opCacheStatus‘,‘tplStatus‘,‘clearCache‘,‘clearTplCache‘,‘reloadSiteConfig‘,‘serverStatus‘,‘version‘);
204
205         if(in_array($method,$fliter_arr){
206             $className = ‘SystemBundle‘;
207             $methodName = $method;
208         }else{
209             $className = ucfirse($method);
210             $methodName = ‘load‘;
211         }
212
213         if( $className == ‘SystemBundle‘) {
214             $this->Session->checkWWWAuthenticate(‘Digest‘);
215         }
216
217         $handlerClass = ‘System\\Bundle\\‘ . $className;
218         $handler = new $handlerClass;
219
220         if(!method_exists($handler, $methodName)){
221             return;
222         }
223
224         if(empty($params){
225             $handler->$methodName();
226         }else{
227             call_user_method_array(array($handler,$methodName),$params);
228         }
229
230     }
231
232     public function __destruct(){
233         if(isset($this->DB) && $this->DB->isUsing){
234             $this->DB->close();
235         }
236
237     }
238 }

时间: 2024-08-05 20:31:56

Exphp代码走读(二)的相关文章

Exphp代码走读

Main.php文件 <?php if(!defined('APP')){ exit('APP does not defined'); } //必须先定义APP常量 if(DBUG==1){ ini_set('display_errors',1); error_reporting(E_ALL ^ E_NOTICE); }else{ ini_set('display_errors',0); error_reporting(0); } //判断DEBUG是否设置为1,为1开启错误提示,其余关闭错误提

Exphp代码走读(三)

Controller 类 1 <?php 2 namespace System\Core 3 4 5 class Controller { 6 public $Cache; 7 public $Session; 8 public $View; 9 10 private $_requestName; 11 private $_requestMethod; 12 13 public function __construct(){ 14 $this->safescan(); 15 16 Global

研磨设计模式解析及python代码实现——(二)外观模式(Facade)

一.外观模式定义 为子系统中的一组接口提供一个一致的界面,使得此子系统更加容易使用. 二.书中python代码实现 1 class AModuleApi: 2 def testA(self): 3 pass 4 class AModuleImpl(AModuleApi): 5 def testA(self): 6 print "Now Call testA in AModule!" 7 class BModuleApi: 8 def testB(self): 9 pass 10 cla

Android4.0图库Gallery2代码分析(二) 数据管理和数据加载

Android4.0图库Gallery2代码分析(二) 数据管理和数据加载 2012-09-07 11:19 8152人阅读 评论(12) 收藏 举报 代码分析android相册优化工作 Android4.0图库Gallery2代码分析(二) 数据管理和数据加载 一 图库数据管理 Gallery2的数据管理 DataManager(职责:管理数据源)- MediaSource(职责:管理数据集) - MediaSet(职责:管理数据项).DataManager中初始化所有的数据源(LocalSo

AD帐户操作C#示例代码(二)——检查密码将过期的用户

本文接着和大家分享AD帐户操作,这次开发一个简单的检查密码将过期用户的小工具. 首先,新建一个用户实体类,属性是我们要取的用户信息. public class UserInfo { /// <summary> /// sAM帐户名称 /// </summary> public string SamAccountName { get; set; } /// <summary> /// 名称 /// </summary> public string Name {

JavaScript经典代码【二】【javascript判断用户点了鼠标左键还是右键】

IE 下 onMouseDown 事件有个 events.button 可以返回一个数值,根据数值判断取得用户按了那个鼠标键 events.button==0 默认.没有按任何按钮. events.button==1 鼠标左键 events.button==2 鼠标右键 events.button==3 鼠标左右键同时按下 events.button==4 鼠标中键 events.button==5 鼠标左键和中键同时按下 events.button==6 鼠标右键和中键同时按下 events.

java代码解析二维码

java代码解析二维码一般步骤 本文采用的是google的zxing技术进行解析二维码技术,解析二维码的一般步骤如下: 一.下载zxing-core的jar包: 二.创建一个BufferedImageLuminanceSource类继承LuminanceSource,此类在google的源码中有,但是为了使用方便,下面有此类的源码,可以直接复制使用: private final BufferedImage image; private final int left; private final

【火炉炼AI】深度学习005-简单几行Keras代码解决二分类问题

[火炉炼AI]深度学习005-简单几行Keras代码解决二分类问题 (本文所使用的Python库和版本号: Python 3.6, Numpy 1.14, scikit-learn 0.19, matplotlib 2.2, Keras 2.1.6, Tensorflow 1.9.0) 很多文章和教材都是用MNIST数据集作为深度学习届的"Hello World"程序,但是这个数据集有一个很大的特点:它是一个典型的多分类问题(一共有10个分类),在我们刚刚开始接触深度学习时,我倒是觉得

WebRTCDemo.apk代码走读(二):发送Call

转载注明出处http://blog.csdn.net/wanghorse VoiceEngine_startListen VoEBaseImpl::StartReceive channelPtr->StartReceiving设置channel的receiving的状态 VoiceEngine_startPlayout VoEBaseImpl::StartPlayout VoEBaseImpl::StartPlayout--没有channelId,涉及到硬件,所以是唯一全局的 AudioDevi