ThinkPHP 类似Yii的Gii生成Model的功能。

2023-05-21,,

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的功能。的相关教程结束。

《ThinkPHP 类似Yii的Gii生成Model的功能。.doc》

下载本文的Word格式文档,以方便收藏与打印。