qeephp 自动成功控制器的方式
多次开发总结的经验,和多次开发中遇到的问题,由于后台权限设置要添加很多个控制器,手动一个一个添加太累,由于一个兄弟的提议,我觉得可行,就研究了一下实现,不是很难,很顺利的就调通了,记录下来,以便以后学习使用
调用方法:
该方法写在了控制器的模型里面,模型的静态调用
Controller::buildControllers();
以下是代码的实现
/**
* 自动成功控制器
* @param string $all
* @return multitype:boolean string multitype:number
*/
static function buildControllers($all=false){
$table_name = array();//定义数据表的名称和注释 code=>name
$module_controller = array();//定义控制器文件数据,二维,第一维是模块,第二维是控制器
$con = QDB::getConn();
$sql = "show table status";
$hand = $con->execute($sql);
$re = $hand->fetchAll();
foreach ($re as $val){
$code = substr($val['Name'],4);
$code = str_replace('_','',$code);
$name = trim($val['Comment']);
$name = $name?$name:$code;
$table_name[$code] = $name;
}
$dir = "../app/controller";
// 打开目录,然后读取其内容
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if (is_dir($dir . "/" . $file)){
if ($d = opendir($dir . "/" . $file)){
while (($f = readdir($d)) !== false){
if (!is_dir($dir . "/" . $file . "/" . $f)){
//echo $file;
if(stripos($file,'.')===false){
$module_controller[$file][] = substr($f,0,-15);
}
}
}
closedir($d);
}
}
}
closedir($dh);
}
}
$result = array();
//生成模块-控制器数据
foreach ($module_controller as $module_code=>$controllers){
$submodule = Submodule::find("code='{$module_code}'")->getOne();
if(!$submodule->id){
$submodule->name = $module_code;
$submodule->code = $module_code;
$submodule->save();
}
$n = 0;
foreach ($controllers as $controller_code){
$controller = Controller::find("code='{$controller_code}' and submodule_id=" . $submodule->id)->getOne();
if(!$controller->id){
$controller_name = isset($table_name[$controller_code])?$table_name[$controller_code]:$controller_code;
$controller->name = $controller_name;
$controller->code = $controller_code;
$controller->submodule_id = $submodule->id;
$controller->status = 1;
$controller->save();
$n++;
if($all){
$result[$module_code][] = $controller_code;
}
}
}
if($all){
$result[$module_code]['count'] = $n;
}else{
$result[$module_code] = $n;
}
}
//统计返回
return array('status' => true,'message'=>'生成成功','data'=>$result);
}记录下学习笔记,以便以后学习使用
请先登录后再评论登录
1楼
打错字了
回复