ThinkPHP 类似Yii的Gii生成Model的功能。
自动生成ThinkPhp 3.1 的基础模型.。
 #!/usr/bin/env php
<?php
/**
*
* THINKPHP 基础模型生成工具
* 使用方法
* 命令行: php 本php文件 表名字
* 然后复制生成好的代码
*
*
*/ $host = 'localhost';
$user = 'root';
$pass = 'root'; $tablePre = 'weixin_';//表前缀
$dbName = 'weixin2'; if($argc < 2)
{
$s = __FILE__;
$str = " 使用方法:php $s tableName";
$num = strlen($str);
print_r(str_repeat('-',$num)."\r\n ThinkPHP 基础模型生成工具\r\n 使用方法:php $s tableName\r\n".str_repeat('-',$num)."\r\n");
return;
} $mysql = new mysqli($host, $user, $pass, $dbName);
$Tii = new ThinkTii($mysql, $tablePre, $argv[1]); $search = array(
'{%fields%}',
'{%tableName%}',
'{%trueTableName%}',
'{%dbName%}',
'{%className%}',
'{%_auto%}',
'{%_validate%}',
'{%property%}');
$replace = array(
$Tii->getFieldString(),
$Tii->getTableName(),
$Tii->getTrueTableName(),
$Tii->getDbName(),
$Tii->getModelClassName(),
$Tii->getAutoFill(),
$Tii->getAutoValidate(),
$Tii->getProperty()); $classString = str_replace($search, $replace, $Tii->getTiiTpl()); echo $classString; function arrayToString($array)
{
$string = "array( "; ksort($array, SORT_NATURAL);
list($key) = each($array);
$key === 0 and $i = 0;
reset($array); foreach ($array as $key => $value) {
if (isset($i) && $key == $i && ++$i) {
$key = '';
} else {
$key = var_export($key, true) . " => ";
unset($i);
}
if (is_array($value)) {
$string .= $key . arrayToString($value) . ', ';
} else {
$string .= $key . var_export($value, true) . ', ';
}
}
$string = trim(trim($string, ' '), ',');
$string .= ")"; return $string;
} /**
* Class ThinkTii
*
* 自动生成ThinkPhp 3.1 的模型
*
*/
class ThinkTii
{ const TYPE_INT = 'integer';
const TYPE_STRING = 'string '; /**
* @var mysqli
*/ protected $mysql = null;
protected $tablePre = '';
protected $dbName = '';
protected $isHump = true;
protected $host = 'localhost';
protected $user = 'root';
protected $pass = 'root';
protected $tableName = '';
protected $trueTableName = ''; public function __construct($mysql, $tablePre, $tableName)
{
$this->tableName = $tableName;
$this->tablePre = $tablePre;
$this->trueTableName = $this->tablePre . $tableName;//要生成哪张表,完整表名
$this->mysql = $mysql;
} public function getDbName()
{
$row = $this->mysql->query("select database();")->fetch_row();
$this->dbName = $row[0];
return $this->dbName;
} public function getTableName()
{
return $this->tableName;
} /**
* 小驼峰转大驼峰
* @param $name
* @return mixed|string
*/
public function humpSmallToBig($name)
{
$str = str_replace('_', ' ', $name);
$str = ucwords($str);
$str = str_replace(' ', '', $str);
return $str;
} public function getDesc($tableName)
{
$sql = "desc " . $this->getTrueTableName($tableName);
$this->mysql->set_charset('utf-8');
$query = $this->mysql->query($sql);
$fetch = array();
while (is_array($row = $query->fetch_array(MYSQL_ASSOC))) {
$fetch[] = $row;
}
return $fetch;
} public function getTiiFields($tableName)
{
$fetch = $this->getDesc($tableName); $fields = array();
foreach ($fetch as $value) {
$fields[] = $value['Field'];
if (strpos($value['Key'], 'PRI') !== false) {
$fields['_pk'] = $value['Field'];
}
if ($value['Extra'] == 'auto_increment') {
$fields['_autoinc'] = true;
}
}
return $fields;
} public function getAutoFill()
{
$fetch = $this->getDesc($this->getTrueTableName());
$array = array();
foreach ($fetch as $field) {
if ($field['Default'] !== null) {
$array[] = array($field['Field'], $field['Default']);
}
}
return arrayToString($array);
} public function getAutoValidate()
{
$fetch = $this->getDesc($this->getTrueTableName());
$requires = $urls = $emails = $numbers = $array = $numbers = $number1s = array();
foreach ($fetch as $field) {
$NotNull = false;
if ($field['Null'] == "NO" && $field['Default'] === null) {
$NotNull = true;
//$array[] = array($field['Field'], 'require', $field['Field'] . ' Can not be a null!', 1);
$requires[] = $field['Field'];
}
if ($field['Key'] == "UNI") {
$array[] = array($field['Field'], '', '值已经存在!', 1, 'unique');
} switch ($this->getType($field['Type'])) {
case self::TYPE_INT:
if ($NotNull) {
$number1s[] = $field['Field'];
} else {
$numbers[] = $field['Field'];
}
break;
case self::TYPE_STRING:
if (strpos($field['Field'], 'mail')) {
$emails[] = $field['Field'];
} elseif (strpos($field['Field'], 'url')) {
$urls[] = $field['Field'];
}
break;
case 'enum':
$string = rtrim(str_replace(array('enum('), '', $field['Type']), ')');
$string = explode(',', $string);
$_tmp = array();
foreach ($string as $str) {
$_tmp[] = trim($str, "'");
}
$array[] = array($field['Field'], $_tmp, '值的范围不正确!', 2, 'in');
unset($_tmp);
break;
}
}
empty($numbers) or $array[] = array(implode(',', $numbers), 'number', ' 格式不对');
empty($number1s) or $array[] = array(implode(',', $number1s), 'number', ' 格式不对', 1);
empty($emails) or $array[] = array(implode(',', $emails), 'email', ' 格式不对');
empty($urls) or $array[] = array(implode(',', $urls), 'url', ' 格式不对');
empty($requires) or $array[] = array(implode(',', $requires), 'require', ' Can not be a null!', 1); return arrayToString($array);
} public function getProperty()
{
$fetch = $this->getDesc($this->getTrueTableName());
$property = array();
foreach ($fetch as $field) {
$type = $this->getType($field['Type']);
$type = $type == 'enum' ? self::TYPE_STRING : $type;
$property[] = " * @property $type \${$field['Field']}";
}
return implode("\r\n", $property);
} protected function getType($typeString)
{
list($type) = explode('(', $typeString);
$types = array(
self::TYPE_INT => array('int'),
self::TYPE_STRING => array('text', 'char', 'varchar')
); foreach ($types as $key => $value) {
if (in_array($type, $value)) {
return $key;
}
}
return $type;
} public function getFieldString()
{
$fieldString = arrayToString($this->getTiiFields($this->tableName));
return $fieldString;
} public function getTrueTableName()
{
return $this->trueTableName;
} public function getModelClassName()
{
if ($this->isHump) {
$className = $this->humpSmallToBig($this->tableName);
} else {
$className = $this->tableName;
}
return $className;
} public function getTiiTpl()
{
$time = date('Y-m-d H:s:i');
$t = <<<__END
<?php /**
*
* Class {%className%}Model
* Tii自动生成。请更具自己实际项目需求进行更改
* 自动验证\$_validate 和自动完成 \$_auto 是更具数据库表默认设置进行生成的。
*
* 按照字段自动生成的类属性。方便IDE代码自动补全
*
{%property%}
*
* @lastTime $time
* @author niy <136045277@qq.com>
*
*/
class {%className%}Model extends Model{
/**
* @var string 表名
*/
protected \$tableName = '{%tableName%}';
/**
* @var string 真实的表名
*/
protected \$trueTableName = '{%trueTableName%}';
/**
* @var string 该模型属于哪个数据库
*/
protected \$dbName = '{%dbName%}';
/**
* @var array 本章表的字段
*/
protected \$fields = {%fields%}; /**
* 自动完成
* @url http://doc.thinkphp.cn/manual/auto_operate.html
* @var array
*/
protected \$_auto = {%_auto%}; /**
* 自动验证
* @url http://doc.thinkphp.cn/manual/auto_validate.html
* @var array
*/
protected \$_validate = {%_validate%}; /**
* 以免破坏程序罗辑,以下函数不需要的请删除。
*/
protected function _before_insert(&\$data, \$options){}
protected function _after_insert(\$data,\$options) {}
protected function _before_update(&\$data,\$options) {}
protected function _after_update(\$data,\$options) {}
protected function _after_select(&\$resultSet,\$options) {}
protected function _after_delete(\$data,\$options) {}
protected function _after_find(&\$result,\$options) {}
} __END;
return $t;
} }

ThinkPHP 类似Yii的Gii生成Model的功能。的更多相关文章

  1. YII 用gii生成modules模块下的mvc

    1.生成model ModelPath设置为: application.modules.[moduleName].models 2.生成CURD ModelClass设置为: application. ...

  2. Yii2 自定义Gii生成代码模板

    我们使用一个例子来介绍如何定制代码模板.假设我们想要定制由 model 生成器生成的代码. 我们首先创建一个名为 protected/gii/model/templates/customer 的目录. ...

  3. yii2使用Gii生成代码

    本章节将介绍怎样使用 Gii 去自己主动生成 Web 网站经常使用功能的代码.使用 Gii 生成代码很easy,仅仅要依照 Gii 页面上的介绍输入正确的信息就可以. 贯穿本章节,你将会学到: 在你的 ...

  4. Yii1使用Gii生成模块实现CURD

    Yii里Gii的强大就不用说了,可以快速生成模块的Model.Controller来开发.要使用Gii,首先你需要创建好操作的数据表. 第一步:创建数据表 CREATE TABLE `t_knowle ...

  5. yii使用gii创建后台模块与widget使用

    yii使用gii创建后台模块与widget使用 1.在protected/config/main.php中打开gii的配置属性. 'gii'=>array( 'class'=>'syste ...

  6. Yii2.0 自动生成 model 层

    yii2.0 里一个表对应一个model,可以自动生成 前台使用的model在frontend(backend)/web目录下的gii生成例如(www.liqiuyue.com/yii /fronte ...

  7. 使用mybatis-generator自动生成model、dao、mapping文件

    参考文献:http://www.cnblogs.com/smileberry/p/4145872.html 一.所需库 1.mybatis-generator库 2.连接DB的驱动(此以mysql为例 ...

  8. 懒人小工具:自动生成Model,Insert,Select,Delete以及导出Excel的方法

    在开发的过程中,我们为了节约时间,往往会将大量重复机械的代码封装,考虑代码的复用性,这样我们可以节约很多时间来做别的事情.最近跳槽到一节webform开发的公司,主要是开发自己公司用的ERP.开始因为 ...

  9. 懒人小工具1:winform自动生成Model,Insert,Select,Delete以及导出Excel的方法

       懒人小工具2:T4自动生成Model,Insert,Select,Delete以及导出Excel的方法    github地址:https://github.com/Jimmey-Jiang/J ...

随机推荐

  1. uva 508 Morse Mismatches

    Samuel F. B. Morse is best known for the coding scheme that carries his name. Morse code is still us ...

  2. Gengxin讲STL系列目录

    引言:有人催我写关于STL的博客#(滑稽)        STL嘛,昨晚有人一直逼问我STL名字的由来——STL = Standard Template Library,标准模板库,惠普实验室开发的一 ...

  3. http://www.cnblogs.com/yyyyy5101/archive/2011/03/11/1981078.html

    http://www.cnblogs.com/yyyyy5101/archive/2011/03/11/1981078.html

  4. [Leetcode] Search In Rotated Sorted Array (C++)

    题目: Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7  ...

  5. 在CentOS 7下试验Drupal 7

    按顺序安装好Apache.MariaDB和PHP,启动Apache和MariaDB,创建一个UTF-8字符集的数据库. > create database if not exists drupa ...

  6. Kindeditor上传图片到七牛云存储插件(PHP版)

    由于工作需要,要使用第三方存储作为图床,发现七牛云挺不错,又可以免费使用10G的空间,决定先试试. 项目中使用的是Kindeditor作为网页编辑器的,七牛云的插件里没有现成的Kindeditor的插 ...

  7. 异常处理与调试4 - 零基础入门学习Delphi53

    调试(Debug) 让编程改变世界 Change the world by program 调试(Debug) 在应用程序开发中检测.处理程序中的错误是一个非常重要的环节.在Delphi的集成开发环境 ...

  8. 1005 Jugs

    辗转相减,新手入门题.两个容量的灌水题,无所谓最优解. #include<stdio.h> int main(){ int A,B,T,sA,sB; ){ sA=sB=; ){ ){ pr ...

  9. css3的loadding效果

    <!DOCTYPE html> <html> <head> <title>CSS3 loading效果</title> <meta c ...

  10. jQuery多版本的使用,同一文件多个版本引用

    <html> <meta http-equiv="Content-Type" content="text/html; charset=utf-8&quo ...