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