自己写的thinkphp自动生成类
模型类:CqhModel.class.php
<?php namespace Cqh\Model; use Think\Model; class CqhModel extends Model { protected $trueTabelName; //对应数据库中的表名 protected $moduleName; //对应的模块名称 protected $tpName; //表对应的TP名 protected $fields; //所有字段信息 protected $tableComment; //表注释 public function iniSet($tableName,$moduleName) { $this->buildDir($moduleName); $this->setAttribute($tableName,$moduleName); return TRUE; } /*********************** 生成控制器 ***********************/ public function gController() { $cDir = APP_PATH . $this->moduleName . '/Controller'; $file = $cDir . '/' . $this->tpName . 'Controller.class.php'; ob_start(); include(APP_PATH . 'Cqh/Template/Controller.php'); $str = ob_get_clean(); if(!is_file($file)) { file_put_contents($file,"<?php\r\n".$str); } return TRUE; } /*********************** 生成模型 ***********************/ public function gModel() { $mDir = APP_PATH.$this->moduleName.'/Model'; if(!is_dir($mDir)) { mkdir($mDir,0755,true); } $file = $mDir . '/' . $this->tpName . 'Model.class.php'; ob_start(); include(APP_PATH . 'Cqh/Template/model.php'); $str = ob_get_clean(); if(!is_file($file)) { file_put_contents($file,"<?php\r\n".$str); } return TRUE; } /*********************** 生成静态页 ***********************/ public function gView() { $vDir = APP_PATH . $this->moduleName . '/View/'.$this->tpName; if(!is_dir($vDir)) { mkdir($vDir,755,TRUE); } $tableComment=$this->tableComment; $arr = array('add','edit','lst'); foreach($arr as $v) { $file = $vDir."/$v.html"; ob_start(); include(APP_PATH . "Cqh/Template/$v.html"); $str = ob_get_clean(); if(!is_file($file)) { file_put_contents($file, $str); } } return TRUE; } /********************** 初始化属性 **********************/ private function setAttribute($tableName,$moduleName) { /**************** 初始化属性$moduleName ****************/ $this->moduleName = $moduleName; /**************** 初始化属性$trueTabelName ****************/ //判断如果没有表前缀就加上 $prefix = C('DB_PREFIX'); if(strpos($tableName,$prefix) !== 0) $this->trueTabelName = $prefix.$tableName; else $this->trueTabelName = $tableName; /**************** 初始化属性$tpName ****************/ //去掉表前缀 if(strpos($tableName,$prefix) === 0) { $len = strlen($prefix); //把表名从前缀开始截取到最后 $tableName = substr($this->trueTabelName, $len); } //去掉下划线 $tableName = explode('_',$tableName); //把$tableName中第一个元素都使用ucfirst处理一遍 $tableName = array_map('ucfirst',$tableName); $tableName = implode('',$tableName); $this->tpName = $tableName; /**************** 初始化属性$fields ****************/ //取出所有的字段的信息 $this->fields = $this->query('SHOW FULL FIELDS FROM '.$this->trueTabelName); /**************** 初始化属性$tableComment ****************/ $result = $this->query("SELECT TABLE_COMMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA='".C('DB_NAME')."' and TABLE_NAME='".$this->trueTabelName."'"); $this->tableComment = $result[0]['TABLE_COMMENT']; return TRUE; } /********************** 创建模块目录 **********************/ public function buildDir($module) { // 没有创建的话自动创建 if(is_writeable(APP_PATH)) { $dirs = array( APP_PATH.$module.'/', APP_PATH.$module.'/Common/', APP_PATH.$module.'/Controller/', APP_PATH.$module.'/Model/', APP_PATH.$module.'/Conf/', APP_PATH.$module.'/View/', ); foreach ($dirs as $dir){ if(!is_dir($dir)) mkdir($dir,0755,true); } } } }
模板类:CqhController.class.php
<?php namespace Cqh\Controller; use Think\Controller; class CqhController extends Controller { public function index() { if(IS_POST) { $tableName = I('post.tableName'); //接收表单中的表名 $moduleName = ucfirst(I('post.moduleName')); //接收模块名 $generaType = I('post.generaType');//接收需要生成的类型 $this->validate($tableName,$moduleName,$generaType);//验证表单 $gModel = D('Cqh'); $gModel->iniSet($tableName,$moduleName); //初始化,传入表名和模块名 if($generaType['controller']) $gModel->gController(); //生成控制器 if($generaType['model']) $gModel->gModel(); //生成模型 if($generaType['view']) $gModel->gView(); //生成视图 $this->success('生成成功',U($moduleName . '/' . $tableName . '/lst')); exit; } $this->display(); } public function validate($tableName,$moduleName,$generaType) { if(!((preg_match('/\S+/',$tableName) === 1))) $this->error('请输入表名'); if(!((preg_match('/\S+/',$moduleName) === 1))) $this->error('请输入模块名'); if(!$generaType) $this->error('请选择要生成的类型'); } }
视图:View/Cqh/index.html
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Cqh代码生成器</title> <style> *{font-size:25px;} .title{font-size:35px;;font-weight: bold;margin:auto auto;} input[type=text]{width:200px;height:30px;font-size:25px;} </style> </head> <body> <div class="title">Cqh代码生成器</div> <form method="post" action="__SELF__"> <table> <tr> <td>表名</td> <td> <input type="text" name="tableName"/> </td> </tr> <tr> <td>模块名</td> <td> <input type="text" name="moduleName"/> </td> </tr> <tr> <td>选择要生成的内容</td> <td> <input type="checkbox" name="generaType[controller]" value="1" checked="checked"/>控制器 <input type="checkbox" name="generaType[model]" value="1" checked="checked"/>模型 <input type="checkbox" name="generaType[view]" value="1" checked="checked"/>视图 </td> </tr> <tr> <td></td> <td> <input type="submit" class="button" value=" 确定 "/> <input type="reset" class="button" value=" 重置 "/> </td> </tr> </table> </form> </body> </html>
模板文件:Template/(controller.php、model.php、add.html、edit.html、lst.html)
1.controller.php
namespace <?php echo $this->moduleName;?>\Controller; use Think\Controller; class <?php echo $this->tpName;?>Controller extends Controller { // 添加 public function add() { if(IS_POST) { $model = D('<?php echo $this->tpName;?>'); if($model->create()) { if($model->add()) { $this->success('添加成功!', U('lst')); exit; } else { $sql = $model->getLastSql(); $this->error('插入数据库失败!.<hr />SQL:'.$sql); } } else { $error = $model->getError(); $this->error($error); } } $this->display(); } public function lst() { $model = D('<?php echo $this->tpName;?>'); $data = $model->search(); $this->assign($data); $this->display(); } public function edit($id) { $model = D('<?php echo $this->tpName;?>'); if(IS_POST) { if($model->create()) { if($model->save() !== FALSE) { $this->success('修改成功!', U('lst')); exit; } else { $sql = $model->getLastSql(); $this->error('修改数据库失败!.<hr />SQL:'.$sql); } } else { $error = $model->getError(); $this->error($error); } } $data = $model->find($id); $this->assign('data', $data); $this->display(); } public function del($id) { $model = D('<?php echo $this->tpName;?>'); $model->delete($id); $this->success('操作成功!', U('lst')); } public function bdel() { $delid = I('post.delid'); if($delid) { $delid = implode(',', $delid); $model = D('<?php echo $this->tpName;?>'); $model->delete($delid); } else $this->error('请选择要删除的记录!'); $this->success('操作成功!', U('lst')); } }
2.model.php
namespace <?php echo $this->moduleName;?>\Model; use Think\Model; class <?php echo $this->tpName;?>Model extends Model { protected $_validate = array( <?php foreach ($this->fields as $k => $v): if($v['Field'] == 'id') continue ; if($v['Null'] == 'NO' && $v['Default'] === null): ?> array('<?php echo $v['Field']; ?>', 'require', '<?php echo $v['Comment']; ?>不能为空!', 1), <?php endif; ?> <?php endforeach; ?> ); public function search() { $where = 1; $orderWay = 'ASC'; // 取出总的记录数 $count = $this->where($where)->count(); // 生成翻页对象 $pageObj = new \Think\Page($count, 25); // 获取翻页的字符串:上一页、下一页 $pageStr = $pageObj->show(); // 取出当前页的数据 $data = $this->where($where)->order("id $orderWay")->limit($pageObj->firstRow.','.$pageObj->listRows)->select(); return array( 'pageStr' => $pageStr, 'data' => $data, ); } protected function _before_insert(&$data, $option) { } protected function _before_update(&$data, $option) { } }
3.add.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>添加<?php echo $this->tableComment;?></title> <meta name="robots" content="noindex, nofollow"> </head> <body> <h1> <span><a href="{:U('lst')}"><?php echo $this->tableComment;?>列表</a></span> <span> - 添加<?php echo $this->tableComment;?></span> </h1> <form method="post" action="__SELF__"> <table> <?php foreach ($this->fields as $k=>$v): if($v['Field'] == 'id') continue; ?> <tr> <td><?php echo $v['Comment'];?></td> <td> <?php if($arr = strstr("{$v['Type']}" ,'enum')) : $arr = substr($arr,6,-2); $arr = explode("','",$arr); foreach($arr as $radioValue=>$radioName):?> <input type="radio" name="<?php echo $v['Field'];?>" value="<?php echo $radioValue+1;?>"/><?php echo $radioName;?> <?php endforeach;?> <?php else: ?> <input type="text" name="<?php echo $v['Field'];?>" /> <?php endif;?> <?php if($v['Null'] == 'NO' && $v['Default'] === null): ?> <span>*</span> <?php endif; ?> </td> </tr> <?php endforeach;?> <tr> <td colspan="2" align="center"><br /> <input type="submit" class="button" value=" 确定 " /> <input type="reset" class="button" value=" 重置 " /> </td> </tr> </table> </form> </body> </html>
4.edit.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>修改<?php echo $this->tableComment;?></title> </head> <body> <h1> <span><a href="{:U('lst')}"><?php echo $this->tableComment;?>列表</a></span> <span> - 修改<?php echo $this->tableComment;?></span> </h1> <div> <form method="post" action="__SELF__"> <input type="hidden" name="id" value="<?php echo '<?php echo $data[\'id\']; ?>'; ?>" /> <table cellspacing="1" cellpadding="3" width="100%"> <?php foreach ($this->fields as $k=>$v): if($v['Field'] == 'id') continue; ?> <tr> <td><?php echo $v['Comment'];?></td> <td> <?php if($arr = strstr("{$v['Type']}" ,'enum')) : $arr = substr($arr,6,-2); $arr = explode("','",$arr); foreach($arr as $radioValue=>$radioName):?> <input type="radio" name="<?php echo $v['Field'];?>" value="<?php echo $radioValue+1;?>" <?php echo '<?php if($data[\''.$v['Field'].'\'] == \''.$radioName.'\')'.'echo \'checked="checked"\'?>'?>/><?php echo $radioName;?> <?php endforeach;?> <?php else: ?> <input type="text" name="<?php echo $v['Field'];?>" maxlength="60" size="40" value="<?php echo '<?php echo $data[\''.$v['Field'].'\']; ?>'; ?>" /> <?php endif;?> <?php if($v['Null'] == 'NO' && $v['Default'] === null): ?> <span>*</span> <?php endif; ?> </td> </tr> <?php endforeach;?> <tr> <td colspan="2" align="center"><br /> <input type="submit" class="button" value=" 确定 " /> <input type="reset" class="button" value=" 重置 " /> </td> </tr> </table> </form> </div> </body> </html>
5.lst.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title><?php echo $this->tableComment;?>列表</title> <meta name="robots" content="noindex, nofollow"> <script type="text/javascript" src="http://misc.360buyimg.com/lib/js/e/jquery-1.6.4-min.js"></script> </head> <body> <h1> <span><a href="{:U('add')}">添加<?php echo $this->tableComment;?></a></span> <span"> - <?php echo $this->tableComment;?>列表 </span> </h1> <form method="post" action="{:U('bdel')}" onsubmit="return confirm('确定要删除吗?');"> <div> <table> <tr> <?php foreach ($this->fields as $k => $v): ?> <th <?php if($v['Comment'] == 'id') echo 'width="100"';?>> <?php if($v['Comment'] == 'id') echo '<input type="checkbox" id="selall"/>';?> <?php echo $v['Comment']; ?> </th> <?php endforeach; ?> <th>操作</th> </tr> <?php echo '<?php foreach ($data as $k => $v): ?>'; ?> <tr> <?php foreach ($this->fields as $k => $v): ?> <td align="center"> <?php if($v['Field'] == 'id') echo <<<CHECKBOX <input name="delid[]" type="checkbox" value="<?php echo \$v['id']; ?>" /> CHECKBOX; ?> <?php echo '<?php echo $v[\''.$v['Field'].'\']; ?>'; ?></td> <?php endforeach; ?> <td align="center"> <a href="{:U('edit',array('id'=>$v['id']))}" title="编辑">编辑</a> <a onclick="return confirm('确定要删除吗?');" href="{:U('del',array('id'=>$v['id']))}" title="移除">移除</a> </td> </tr> <?php echo '<?php endforeach; ?>'; ?> <tr> <td><input type="submit" value="删除所选" /></td> <td colspan="<?php echo $k+2; ?>"> <?php echo '<?php echo $pageStr; ?>'; ?> </td> </tr> </table> </div> </form> </body> </html> <script> $('#selall').click(function () { $('input[name="delid[]"]').prop('checked', this.checked); }); </script>