1. ThinkPHP 类似YiiGii生成Model的功能。
    自动生成ThinkPhp 3.1 的基础模型.。
  1. #!/usr/bin/env php
  2. <?php
  3. /**
  4. *
  5. * THINKPHP 基础模型生成工具
  6. * 使用方法
  7. * 命令行: php 本php文件 表名字
  8. * 然后复制生成好的代码
  9. *
  10. *
  11. */
  12.  
  13. $host = 'localhost';
  14. $user = 'root';
  15. $pass = 'root';
  16.  
  17. $tablePre = 'weixin_';//表前缀
  18. $dbName = 'weixin2';
  19.  
  20. if($argc < 2)
  21. {
  22. $s = __FILE__;
  23. $str = " 使用方法:php $s tableName";
  24. $num = strlen($str);
  25. print_r(str_repeat('-',$num)."\r\n ThinkPHP 基础模型生成工具\r\n 使用方法:php $s tableName\r\n".str_repeat('-',$num)."\r\n");
  26. return;
  27. }
  28.  
  29. $mysql = new mysqli($host, $user, $pass, $dbName);
  30. $Tii = new ThinkTii($mysql, $tablePre, $argv[1]);
  31.  
  32. $search = array(
  33. '{%fields%}',
  34. '{%tableName%}',
  35. '{%trueTableName%}',
  36. '{%dbName%}',
  37. '{%className%}',
  38. '{%_auto%}',
  39. '{%_validate%}',
  40. '{%property%}');
  41. $replace = array(
  42. $Tii->getFieldString(),
  43. $Tii->getTableName(),
  44. $Tii->getTrueTableName(),
  45. $Tii->getDbName(),
  46. $Tii->getModelClassName(),
  47. $Tii->getAutoFill(),
  48. $Tii->getAutoValidate(),
  49. $Tii->getProperty());
  50.  
  51. $classString = str_replace($search, $replace, $Tii->getTiiTpl());
  52.  
  53. echo $classString;
  54.  
  55. function arrayToString($array)
  56. {
  57. $string = "array( ";
  58.  
  59. ksort($array, SORT_NATURAL);
  60. list($key) = each($array);
  61. $key === 0 and $i = 0;
  62. reset($array);
  63.  
  64. foreach ($array as $key => $value) {
  65. if (isset($i) && $key == $i && ++$i) {
  66. $key = '';
  67. } else {
  68. $key = var_export($key, true) . " => ";
  69. unset($i);
  70. }
  71. if (is_array($value)) {
  72. $string .= $key . arrayToString($value) . ', ';
  73. } else {
  74. $string .= $key . var_export($value, true) . ', ';
  75. }
  76. }
  77. $string = trim(trim($string, ' '), ',');
  78. $string .= ")";
  79.  
  80. return $string;
  81. }
  82.  
  83. /**
  84. * Class ThinkTii
  85. *
  86. * 自动生成ThinkPhp 3.1 的模型
  87. *
  88. */
  89. class ThinkTii
  90. {
  91.  
  92. const TYPE_INT = 'integer';
  93. const TYPE_STRING = 'string ';
  94.  
  95. /**
  96. * @var mysqli
  97. */
  98.  
  99. protected $mysql = null;
  100. protected $tablePre = '';
  101. protected $dbName = '';
  102. protected $isHump = true;
  103. protected $host = 'localhost';
  104. protected $user = 'root';
  105. protected $pass = 'root';
  106. protected $tableName = '';
  107. protected $trueTableName = '';
  108.  
  109. public function __construct($mysql, $tablePre, $tableName)
  110. {
  111. $this->tableName = $tableName;
  112. $this->tablePre = $tablePre;
  113. $this->trueTableName = $this->tablePre . $tableName;//要生成哪张表,完整表名
  114. $this->mysql = $mysql;
  115. }
  116.  
  117. public function getDbName()
  118. {
  119. $row = $this->mysql->query("select database();")->fetch_row();
  120. $this->dbName = $row[0];
  121. return $this->dbName;
  122. }
  123.  
  124. public function getTableName()
  125. {
  126. return $this->tableName;
  127. }
  128.  
  129. /**
  130. * 小驼峰转大驼峰
  131. * @param $name
  132. * @return mixed|string
  133. */
  134. public function humpSmallToBig($name)
  135. {
  136. $str = str_replace('_', ' ', $name);
  137. $str = ucwords($str);
  138. $str = str_replace(' ', '', $str);
  139. return $str;
  140. }
  141.  
  142. public function getDesc($tableName)
  143. {
  144. $sql = "desc " . $this->getTrueTableName($tableName);
  145. $this->mysql->set_charset('utf-8');
  146. $query = $this->mysql->query($sql);
  147. $fetch = array();
  148. while (is_array($row = $query->fetch_array(MYSQL_ASSOC))) {
  149. $fetch[] = $row;
  150. }
  151. return $fetch;
  152. }
  153.  
  154. public function getTiiFields($tableName)
  155. {
  156. $fetch = $this->getDesc($tableName);
  157.  
  158. $fields = array();
  159. foreach ($fetch as $value) {
  160. $fields[] = $value['Field'];
  161. if (strpos($value['Key'], 'PRI') !== false) {
  162. $fields['_pk'] = $value['Field'];
  163. }
  164. if ($value['Extra'] == 'auto_increment') {
  165. $fields['_autoinc'] = true;
  166. }
  167. }
  168. return $fields;
  169. }
  170.  
  171. public function getAutoFill()
  172. {
  173. $fetch = $this->getDesc($this->getTrueTableName());
  174. $array = array();
  175. foreach ($fetch as $field) {
  176. if ($field['Default'] !== null) {
  177. $array[] = array($field['Field'], $field['Default']);
  178. }
  179. }
  180. return arrayToString($array);
  181. }
  182.  
  183. public function getAutoValidate()
  184. {
  185. $fetch = $this->getDesc($this->getTrueTableName());
  186. $requires = $urls = $emails = $numbers = $array = $numbers = $number1s = array();
  187. foreach ($fetch as $field) {
  188. $NotNull = false;
  189. if ($field['Null'] == "NO" && $field['Default'] === null) {
  190. $NotNull = true;
  191. //$array[] = array($field['Field'], 'require', $field['Field'] . ' Can not be a null!', 1);
  192. $requires[] = $field['Field'];
  193. }
  194. if ($field['Key'] == "UNI") {
  195. $array[] = array($field['Field'], '', '值已经存在!', 1, 'unique');
  196. }
  197.  
  198. switch ($this->getType($field['Type'])) {
  199. case self::TYPE_INT:
  200. if ($NotNull) {
  201. $number1s[] = $field['Field'];
  202. } else {
  203. $numbers[] = $field['Field'];
  204. }
  205. break;
  206. case self::TYPE_STRING:
  207. if (strpos($field['Field'], 'mail')) {
  208. $emails[] = $field['Field'];
  209. } elseif (strpos($field['Field'], 'url')) {
  210. $urls[] = $field['Field'];
  211. }
  212. break;
  213. case 'enum':
  214. $string = rtrim(str_replace(array('enum('), '', $field['Type']), ')');
  215. $string = explode(',', $string);
  216. $_tmp = array();
  217. foreach ($string as $str) {
  218. $_tmp[] = trim($str, "'");
  219. }
  220. $array[] = array($field['Field'], $_tmp, '值的范围不正确!', 2, 'in');
  221. unset($_tmp);
  222. break;
  223. }
  224. }
  225. empty($numbers) or $array[] = array(implode(',', $numbers), 'number', ' 格式不对');
  226. empty($number1s) or $array[] = array(implode(',', $number1s), 'number', ' 格式不对', 1);
  227. empty($emails) or $array[] = array(implode(',', $emails), 'email', ' 格式不对');
  228. empty($urls) or $array[] = array(implode(',', $urls), 'url', ' 格式不对');
  229. empty($requires) or $array[] = array(implode(',', $requires), 'require', ' Can not be a null!', 1);
  230.  
  231. return arrayToString($array);
  232. }
  233.  
  234. public function getProperty()
  235. {
  236. $fetch = $this->getDesc($this->getTrueTableName());
  237. $property = array();
  238. foreach ($fetch as $field) {
  239. $type = $this->getType($field['Type']);
  240. $type = $type == 'enum' ? self::TYPE_STRING : $type;
  241. $property[] = " * @property $type \${$field['Field']}";
  242. }
  243. return implode("\r\n", $property);
  244. }
  245.  
  246. protected function getType($typeString)
  247. {
  248. list($type) = explode('(', $typeString);
  249. $types = array(
  250. self::TYPE_INT => array('int'),
  251. self::TYPE_STRING => array('text', 'char', 'varchar')
  252. );
  253.  
  254. foreach ($types as $key => $value) {
  255. if (in_array($type, $value)) {
  256. return $key;
  257. }
  258. }
  259. return $type;
  260. }
  261.  
  262. public function getFieldString()
  263. {
  264. $fieldString = arrayToString($this->getTiiFields($this->tableName));
  265. return $fieldString;
  266. }
  267.  
  268. public function getTrueTableName()
  269. {
  270. return $this->trueTableName;
  271. }
  272.  
  273. public function getModelClassName()
  274. {
  275. if ($this->isHump) {
  276. $className = $this->humpSmallToBig($this->tableName);
  277. } else {
  278. $className = $this->tableName;
  279. }
  280. return $className;
  281. }
  282.  
  283. public function getTiiTpl()
  284. {
  285. $time = date('Y-m-d H:s:i');
  286. $t = <<<__END
  287. <?php
  288.  
  289. /**
  290. *
  291. * Class {%className%}Model
  292. * Tii自动生成。请更具自己实际项目需求进行更改
  293. * 自动验证\$_validate 和自动完成 \$_auto 是更具数据库表默认设置进行生成的。
  294. *
  295. * 按照字段自动生成的类属性。方便IDE代码自动补全
  296. *
  297. {%property%}
  298. *
  299. * @lastTime $time
  300. * @author niy <136045277@qq.com>
  301. *
  302. */
  303. class {%className%}Model extends Model{
  304. /**
  305. * @var string 表名
  306. */
  307. protected \$tableName = '{%tableName%}';
  308. /**
  309. * @var string 真实的表名
  310. */
  311. protected \$trueTableName = '{%trueTableName%}';
  312. /**
  313. * @var string 该模型属于哪个数据库
  314. */
  315. protected \$dbName = '{%dbName%}';
  316. /**
  317. * @var array 本章表的字段
  318. */
  319. protected \$fields = {%fields%};
  320.  
  321. /**
  322. * 自动完成
  323. * @url http://doc.thinkphp.cn/manual/auto_operate.html
  324. * @var array
  325. */
  326. protected \$_auto = {%_auto%};
  327.  
  328. /**
  329. * 自动验证
  330. * @url http://doc.thinkphp.cn/manual/auto_validate.html
  331. * @var array
  332. */
  333. protected \$_validate = {%_validate%};
  334.  
  335. /**
  336. * 以免破坏程序罗辑,以下函数不需要的请删除。
  337. */
  338. protected function _before_insert(&\$data, \$options){}
  339. protected function _after_insert(\$data,\$options) {}
  340. protected function _before_update(&\$data,\$options) {}
  341. protected function _after_update(\$data,\$options) {}
  342. protected function _after_select(&\$resultSet,\$options) {}
  343. protected function _after_delete(\$data,\$options) {}
  344. protected function _after_find(&\$result,\$options) {}
  345. }
  346.  
  347. __END;
  348. return $t;
  349. }
  350.  
  351. }

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. 最强烈推荐-我的java收藏夹(内有国内最好的java论坛)

    原地址: http://bbs.chinaitlab.com/dispbbs.asp?boardid=148&id=34276 国内: www.chinajavaworld.com-论坛人很多 ...

  2. (原创) mac 10.9.2 eclipse 的 CDT 的 异常的修复

    测试平台:macbook air 2012 , os x 10.9.2 , eclipse 4.3   在升级了 10.9 之后,eclipse 的CDT 无法正常使用了   异常表现:   1. 文 ...

  3. linux下virtualenv的python版本

    virtualenv是python开发中一个重要的工具,它可以帮助我们创建一个干净的python解释环境,创建虚拟环境时,这个虚拟环境的 python版本往往是系统默认的2.x版本.别急,我们只需要一 ...

  4. NopCommerce 3.3中文语言包发布下载及使用

    NopCommerce 3.3是一套国外优秀的开源电子商务项目,其拥有完整的电子商务功能且具有灵活的配置功能,基于微软最新技术ASP.NET MVC 5.1.1,EntityFramework.6.1 ...

  5. mongodb操作记录

    [User]1.db.addUser("name","pwd","true/false")2.db.auth("name" ...

  6. load Event

    document.addEventListener("DOMContentLoaded");------------------load document.body.addEven ...

  7. HtmlNodeType枚举

    HtmlNodeType是一个枚举,用于说明一个节点的类型. 源代码如下所示: public enum HtmlNodeType { Document = 0, Element = 1, Commen ...

  8. 【Xamarin挖墙脚系列:关闭 OS X El Capitan 中 SIP 安全设置功能】

    比如需要修改内核配置文件: com.apple.Boot.plist 那么我们需要解锁权限. 禁止SIP模式,那么就可以修改此文件了. 在 OS X El Capitan 中有一个跟安全相关的模式叫 ...

  9. Go代理,修改标题

  10. [Ubuntu]在Ubuntu下搭建自己的源服务器

    1.摘要     网上有很很多关于搭建源镜像的文章,但是对于一般人来讲,用不着镜像所有的deb包,只对我们能用到的感兴趣.另外,对于一些在Ubuntu的源中没有的软件,我们也可以放在我们自己的源里,这 ...