zhphpframework (十一) 控制器 controller 层,类的映射
2015-12-11 13:46
495 查看
<?php /** * Created by JetBrains PhpStorm. * User: 张华 * Date: 14-3-8 * Time: 下午12:21 * QQ: 746502560@qq.com * To change this template use File | Settings | File Templates. */ defined('IN_ZHPHP')?NULL:die('attempts to hack the system'); class controller{ protected $db;#数据库实例化对象属性 protected $models=array();#模型实例化对象数组 protected $components=array();#数据组件实例化对象数组 protected $layout;#布局名称 protected $smarty;#smarty 对象 protected $users; #这是你的模型声明属性 private $attrs=array(); private static $temp=array(); /** * 私有拦截器 * 私有设置处理魔法方法 * @param type $key * @param type $value */ public function __set($key,$value){ $this->attrs[$key]=$value; unset($key,$value); } /** * 私有是否存在 * @param $key * @return bool */ public function __isset($key){ return isset($this->attrs[$key]); } /** * 私有捕获器 * 获取私有处理魔法方法 * @param type $key * @return type */ public function __get($key){ if (array_key_exists($key, $this->attrs)) { return $this->attrs[$key]; } } /** * 如果类中没有找到动作就执行空操作 * @param unknown_type $name * @param unknown_type $args */ public function __call($name,$args){ $this->_empty(); } /** * 子类自己实现空操作 */ protected function _empty(){} /** * 判断是否是get提交数据 * @return type */ protected function isGet(){ return (strtolower($_SERVER['REQUEST_METHOD']) == 'get') ? true : false; } /** * 获取get值 * @param type $key * @return type */ protected function _get($key=''){ $key=empty($key)?$_GET:$key; $getVal=(is_array($key) && empty($key))?null:$key; if(is_array($getVal)) return $getVal; $getVal= isset($_GET[$key])?$_GET[$key]:null; unset($key); $getVal=filterKword($getVal); return addslashes($getVal); } /** * 判断是否是post提交数据 * @return type */ protected function isPost(){ return (strtolower($_SERVER['REQUEST_METHOD']) == 'post') ? true : false; } /** * 获取post提交的数据 * @param type $data */ protected function _post($data=array()){ $data=empty($data)?$_POST:$data; $data=rebuild_array($data,true); foreach ( $data as $key => $value ){ if (get_magic_quotes_gpc()){ $value = htmlspecialchars($value); }else{ $value = htmlspecialchars(addslashes($value)); } $data[$key]=$value; } return $data; } /** * 判断是否是ajax * @return boolean */ protected function isAjax(){ if ($_SERVER['HTTP_X_REQUESTED_WITH'] && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){ return true; } } /** * @param $name * @param $value */ protected function assign($name,$value){ $this->smarty->assign($name,$value); } /** *处理编译模板 不输出 */ public function renderPartial($tpl,$vars=array(),$cacheId=''){ #处理参数 if( ! empty ($vars)){ foreach ($vars as $k=>$v){ $this->smarty->assign($k,$v); } } if(empty($cacheId)){ $tpl= ucfirst($tpl);#首字母转换成大写 $arr=explode('/', $tpl); $action=end($arr);#得到模板路径中的action $cacheId=$action; } #构建模板文件名 $fileName=config::readConfig('Smarty','php_templates')== true?$tpl.'.php':$tpl.'.html'; return $this->_fetch($fileName,$cacheId); } /** * 视图渲染层 * @param type $template * @param type $args */ protected function render($tpl='',$vars=array(),$cacheId=''){ $layoutName='';#layout模板名 $parentLayout='';#父级layout模板文件 $router=engine::load('router'); #处理模版路径 if($tpl == ''){ $control=$router->getControl();#获取控制器 $action=$router->getAction();#获取动作名 $tpl=$control.'/'.$action.''; }else{ $tpl= ucfirst($tpl);#首字母转换成大写 $arr=explode('/', $tpl); $action=end($arr);#得到模板路径中的action } #处理参数 if( ! empty ($vars)){ foreach ($vars as $k=>$v){ $this->smarty->assign($k,$v); } } #构建模板文件名 $fileName=config::readConfig('Smarty','php_templates')== true?$tpl.'.php':$tpl.'.html'; #最高级layout $layoutName=config::readConfig('app','layout'); #如果是后台就手动继承模板 $routerModule=$router->getModule(); $confAdminModel=config::readConfig('app','admin_module'); if($routerModule == $confAdminModel){#后台状况 $this->_display($fileName,$action,$cacheId,null); unset($routerModule); }else if(empty($layoutName)){#不存在顶级layout,也就是说配置文件中没有配置layout,#前端部存在layout #前端实现静态化 if($this->layout){#是否存在当前控制器指定layout $parentLayout='layout/'.$this->layout.'.html'; $this->_display($fileName,$action,$cacheId,$parentLayout); }else{ #不存在配置文件的layout也没有在控制器中申明layout $this->_display($fileName,$action,$cacheId,null); } }else{#存在顶级layout #去判断当前的控制器是否改变layout布局 如果改变那么就是要新的layout否则就使用配置文件中的layout $nowlayoutName=(empty($this->layout))?$layoutName:$this->layout; $parentLayout='layout/'.$nowlayoutName.'.html'; $this->_display($fileName,$action,$cacheId,$parentLayout); } $this->smarty=null; unset($tpl,$vars,$cacheId,$fileName,$action,$layoutName,$parentLayout,$parentparentLayout,$arr,$control); } /** * @param $parentLayout * @param $fileName * @param $action#作为缓存 id * @param $cacheId * @return mixed */ private function _display($fileName,$action,$cacheId,$parentLayout){ $staticHtmls=config::readConfig('staticHtml'); $nostaticHtmls=config::readConfig('noCacheStaticHtml'); if($staticHtmls == false || empty($staticHtmls) || APP_DEBUG == true || empty($nostaticHtmls)){ //表示不需要写静态 html::runTpl($fileName,$action,$cacheId,$parentLayout,serialize($this->smarty)); }elseif(APP_DEBUG == false){ $routerinfo=createModule_Control_Action(serialize(engine::load('router'))); $nocache1=$routerinfo['moduleName'].'/'.$routerinfo['controlName'].'/'.$routerinfo['actionName']; $nocache2=$routerinfo['moduleName'].'/'.$routerinfo['controlName']; if(in_array($routerinfo['moduleName'],$nostaticHtmls) || in_array($routerinfo['controlName'],$nostaticHtmls) || in_array($routerinfo['actionName'],$nostaticHtmls) || in_array($nocache1,$nostaticHtmls) || in_array($nocache2,$nostaticHtmls)){ html::runTpl($fileName,$action,$cacheId,$parentLayout,serialize($this->smarty)); }elseif($staticHtmls[0] == 1){ html::actionStaticFile($fileName,serialize($this->smarty)); }else{ if(in_array($routerinfo['moduleName'],$staticHtmls)){ html::actionStaticFile($fileName,serialize($this->smarty)); } } } exit; } private function _fetch($fileName,$cacheId){ return $this->smarty->fetch($fileName,$cacheId); } /** * url 重定向 * @param type $url * @param type $status */ protected function redirect($url = null, $status = 302){ header('Status: ' . $status); #header头发送状态status信息为 302# if(stripos($url,HTTP_URL) === false){ $referer=$this->referer(); $http_request=str_ireplace('.html',null,(stripos($referer,$url)=== false)?HTTP_URL:str_ireplace($url,'', $this->referer())); unset($referer); header('Location: ' .$http_request.str_replace('&', '&', $url)); }else{ header('Location: ' .str_replace('&', '&', $url)); } unset($url,$status); exit(); } /** * ajax返回 * @param unknown_type $ajaxReturnType 返回的类型 默认为 string 可选有 json * @param unknown_type $ajaxReturnData 返回的数据 注意: 如果是xml 或者 json 那么数据必须是数组 */ protected function ajaxReturn($ajaxReturnData = null,$ajaxReturnType = 'string'){ if ($ajaxReturnType == 'string'){ return $ajaxReturnData; }elseif ($ajaxReturnType == 'json'){ foreach ($ajaxReturnData as $key => $value){ if (is_array($value)){ $this->ajaxReturn( $value,'json'); } $json_value = urlencode($value); $jsonstr = json_encode($json_value); $json = urldecode($jsonstr); } return $json; } } /** * 手动调用数据库链接对象 * @return type */ protected function database(){ return database::init(); } /** * 在什么动作之前 */ protected function before_(){} /** * 在什么动作之后 */ protected function after_(){} /** * 控制器调用模型 * @param type $modelName * @return type */ protected function model($modelName){ if(is_string($modelName)){ return $this->getModelName($modelName); }else if(is_array($modelName)){ $objects=array(); foreach($modelName as $model){ $umodle=$this->getModelName($model); $objects[]=$umodle; } unset ($modelName,$model,$UmodelName); return $objects; } } /** * @param $modelName * @return type * 得到真实的模型名称,并产生对象 */ private function getModelName($modelName){ $umodle=engine::load($this->loadModel($modelName)); unset($modelName); return $umodle; } /** * 加载模型 * @param $modelName * @return string */ private function loadModel($modelName){ $UmodelName=ucfirst($modelName).'Model'; $module=$GLOBALS['router']->getModule(); if( ! empty($module)){ include_once APP_PATH.'modules/'.$module.'/models/'.$UmodelName.'.class.php'; } unset($module); return $UmodelName; } /** * 加载components */ private function loadComponent($componentName){ $UcomponentName=ucfirst($componentName); $module=$GLOBALS['router']->getModule(); if( ! empty($module)){ return $UcomponentName.'Component'; } unset($module); return $UcomponentName; } /** * 兼容zhphp1.0版本 */ private function loadcomponents(){ #读取所有模块 // $modules=config::readConfig('modules'); // $incldePath=array(); // foreach($modules as $module){ // $dir=APP_PATH."modules/".$module; // if(is_dir($dir)){ // $incldePath[]=$dir."/controllers/components/"; // } // } // $incldePath[]=APP_PATH."controllers/components/"; // foreach($incldePath as $path){ // foreach($this->components as $component ){ // $file=$path.ucfirst($component).'Component.php'; // if(file_exists($file)){ // include_once $file; // } // } // } //unset($modules,$incldePath,$file); } /** * 映射compontent对象 */ protected function Reflectioncomponents(){ if( ! empty($this->components)){ if(is_string($this->components)){ $componentName=$this->components; $truecomponentName=$this->loadComponent($componentName); //优化程序,减少程序类的调用次数 if(isset(self::$temp[$this->components])){ $ucomponentObject=unserialize(self::$temp[$this->components]); }else{ $ucomponentObject=engine::load($truecomponentName); $serializeComponent=serialize($ucomponentObject); self::$temp[$this->components]=$serializeComponent; } $this->$componentName=$ucomponentObject; unset($componentName,$truecomponentName,$ucomponentObject); }elseif(is_array($this->components)){ $componentslength=count($this->components); for($i=0;$i<$componentslength;$i++){ /** * 兼容php5.2 */ $componentName=$this->components[$i]; $truecomponentName=$this->loadComponent($componentName); //优化程序,减少程序类的调用次数 if(isset(self::$temp[$componentName])){ $ucomponentObject=unserialize(self::$temp[$componentName]); }else{ $ucomponentObject=engine::load($truecomponentName); $serializeComponent=serialize($ucomponentObject); self::$temp[$componentName]=$serializeComponent; } $this->$componentName=$ucomponentObject; } unset($componentName,$truecomponentName,$ucomponentObject); } } } /** * 构造方法 */ public function __construct(){ $this->smarty=unserialize(template::setTpl());#获取smarty模版对象; $this->db=unserialize(database::init());#初始化控制的数据库 $this->ReflectionModel();#反射模型表对象 $this->Reflectioncomponents();#反射components逻辑优化类 $this->beforeFilter();#全局在类执行之前执行 } public function __descruct(){ $this->afterFilter();#全局 在类执行完成之后执行 } /** * 实现全局方法 * 因为 控制器的父类占用了 __construct() * 在控制器实例化的时候执行 */ public function beforeFilter(){} /** * 实现全局方法 * 在控制器实例化之后,当前类执行完成之后再执行 */ public function afterFilter(){} /** * 获取url段 */ protected function segment($segment=''){ $module=$GLOBALS['router']->getModule();#获取模块 $control=ucfirst($GLOBALS['router']->getControl());#获取控制器 $action=$GLOBALS['router']->getAction();#获取动作名 $module=empty($module)?null:$module; $control=empty($control)?'index':$control; $action=empty($action)?'index':$action; switch ($segment){ case 'm': $ment=$module; break; case 'c': $ment=$control;break; case 'a': $ment=$action; break; default: $ment=array($module,$control,$action);break; } unset($module,$control,$action,$segment); return $ment; } /** * 得到当前页面的上一个链接 * @return null */ protected function referer(){ return empty($_SERVER['HTTP_REFERER'])?null:$_SERVER['HTTP_REFERER']; } /** * 反射得到模型对象 */ private function ReflectionModel(){ if( ! empty($this->users)){ if(is_string($this->users)){ $modelName=$this->users; $trueModelName=$this->loadModel($modelName); $umodelObje=engine::load($trueModelName); $this->$modelName=$umodelObje; unset($modelName,$trueModelName,$umodelObje); }elseif(is_array($this->users)){ $userslength=count($this->users); for($i=0;$i<$userslength;$i++){ /** * 兼容php5.2 */ $modelName=$this->users[$i]; $trueModelName=$this->loadModel($modelName); $umodelObje=engine::load($trueModelName); $this->$modelName=$umodelObje; } unset($modelName,$trueModelName,$umodelObje); } } } /** * @param $callable * @param $calldata * @return mixed * @注册事件 */ protected function setEventHandler($callable,$calldata){ $this->components=is_string($callable[0])?ucfirst($callable[0]):die('error:语法错误'); $this->Reflectioncomponents();#映射 $componentName=$this->components; $callback=$this->$componentName->$callable[1]($calldata[0],$calldata[1]); unset($componentName); return $callback; } /** * * * * @return */ public function error(){ } }
相关文章推荐
- zhphp framework(九) html静态处理相关类,自动页面静态化处理
- ThinkPHP 十一基于角色的控制访问
- zhphp framework (八) 路由引擎
- 高效的php 导出 xls,csv 的方法
- zhphp framework (七) 配置文件加载与读取以及动态写、读配置文件
- 基于ace后台管理系统模板--CMS(Thinkphp框架)的筹划
- zhphp frmaework (六) help帮助函数包,以及系统应用函数包
- zhphp framework (五) 框架加载类
- zhphp framework (四)动态加载应用程序产量,方便任何程序代码重构
- zhphp framework (三) 框架工作流程
- ThinkPHP
- 夺命雷公狗---PHP---玩转安卓2之扫码进行登录原理
- php laravel 帧 该文件上传
- php创建空对象
- Gearmand和PECL extension for Gearman版本不兼容的问题
- php扩展名获取函数
- php利用pdo进行mysql的事务处理机制
- phpstorm移除已创建的项目
- PHP漏洞全解(六)-Session劫持
- PHP漏洞全解(四)-SQL注入攻击