自己写的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')}" οnsubmit="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 οnclick="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>

转载于:https://www.cnblogs.com/chenqionghe/p/4374422.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
支持MySQL 和 sqlite数据库,快速构建项目原型,直接生成前后台CRUD代码片段,还可根据需要自行定制代码模板,减少重复劳动。 这个东西的原因是因为我最近沮丧的发现很多时候我都在做重复的事情,比如重复最简单的CRUD方法,编表单,前台样式表等等。 2014年9月27日23:53:38更新:升级至0.3版,此次变化较大,放弃了单文件的形式,但是功能更加丰富,支持直接生成文件,快速构建项目原型 ThinkphpHelper ============== 支持MySQL 和 sqlite数据库,快速构建项目原型,直接生成前后台CRUD代码片段,还可根据需要自行定制代码模板,减少重复劳动。 这个东西的原因是因为我最近沮丧的发现很多时候我都在做重复的事情,比如重复最简单的CRUD方法,编表单,前台样式表等等。 Thinkphp对于后台操作的支持已经非常强大,再加上最近非常流行的Bootstrap框架让前台样式也变得容易遵循一个标准,于是我决定开始一个属于自己的代码生成器。 我希望它操作足够简单,让人一看就懂,对MySql和Sqlite数据库都能够稳定生成CRUD代码就好,还如果还能顺便生成一些符合Bootstrap框架的View代码就更好啦。 ThinkphpHelper诞生至今多谢大家的支持。在这个版本中我放弃了单文件的形式,以便实现更多想法。你可以看到现在界面更漂亮了,功能也更强大了。这个版本最大的亮点就是支持直接生成文件,除了数据库外,你只需要3行左右的代码就可以快速构建出一个原型系统。我建议你可以根据你的需要自行修改Template文件夹下的模板,使之更符合你的项目需求。 测试中我使用的是Sqlite数据库,复制数据库文件到项目目录下,如使用Mysql数据库可以省略此步骤。 将TPH文件夹复制到项目目录下。 修改项目配置文件,主要是配置数据库信息。 访问一下TPH,应该看到以上界面 点击“生成模块选项”选择好目标模块,把需要生成的表名打上勾,点击生成。成功后,会有提示生成路径。此步骤主要是为了生成布局文件。 点击“生成CRUD代码”,注意选择和上一步相同的数据表,点击生成文件。 修改Index控制器下的index方法内容为:$this->show();如图 再次访问你的项目,have fun. 注意,在使用之前一定要准备好你的数据库以及数据库里的数据表,并且配置好你的模块,不过聪明的你一定知道它是怎么用的对吧? 支持Thinkphp3.2.2 ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ 项目地址:https://github.com/zhuanqianfish/ThinkphpHelper 详细使用说明地址:http://zhuanqianfish.github.io/ThinkphpHelper ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ ThinkphpHelper遵循Apache2开源协议发布,并提供免费使用。 标签:Web框架

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值