ThinkPHP为了节省一些重复的步骤,写了个简单版的生成model的工具,逆向生成model代码,节省时间,专注写业务代码。
ThinkPHP中的命令行也提供了一些生成代码的命令:
make:controller 创建控制器
make:model 创建模型
make:middleware 创建中间件
ThinkPHP也提供了逆向生成model的命令:optimize:autoload,但是提示:Command “optimize:autoload” is not defined.
于是就算了,也不想去研究它。还不如直接写一个。
下面是一个简单的逆向工程工具实现代码:
<?php
namespace app\controller;
use app\BaseController;
use think\Request;
use think\Facade\Db;
class GeneratorController extends BaseController
{
static $schema = "shushan";
public function generator()
{
//获取表名
$tables = Db::query("SELECT TABLE_NAME as 'name'
from information_schema.tables
WHERE TABLE_SCHEMA = :dataBase", ["dataBase" => GeneratorController::$schema]);
foreach ($tables as $key => $value) {
foreach ($value as $item) {
//获取字段名称和备注
$COLUMNS = Db::query("select COLUMN_NAME,DATA_TYPE,COLUMN_COMMENT
from information_schema.COLUMNS
where table_name = :item
and table_schema = :dataBase", ["item" => $item, "dataBase" => GeneratorController::$schema]);
$file = fopen("tempFile/" . GeneratorController::snakeToCamel($item) . ".php", "w");
fwrite($file, "<?php" . PHP_EOL . "namespace app\model;" . PHP_EOL
. PHP_EOL . "use think\model;" . PHP_EOL
. PHP_EOL . "class " . GeneratorController::snakeToCamel($item) . " extends Model"
. PHP_EOL . "{" . PHP_EOL);
$content = "//设置字段信息" . PHP_EOL .
"protected $" . "schema = [" . PHP_EOL;
fwrite($file, $content);
//写入字段
foreach ($COLUMNS as $COLUMN) {
$content = "'" . $COLUMN["COLUMN_NAME"] . "'" . " =>" .
"'" . $COLUMN["DATA_TYPE"] . "'" . "," . "//" . $COLUMN["COLUMN_COMMENT"] . PHP_EOL;
fwrite($file, $content);
}
$content = PHP_EOL . "];";
fwrite($file, $content);
fwrite($file, PHP_EOL . "}");
fclose($file);
}
}
return $this->success();
}
static function snakeToCamel($str, $capitalized = true)
{
$result = str_replace('_', '', ucwords($str, '_'));
if (!$capitalized) {
$result = lcfirst($result);
}
return $result;
}
}
生成的效果: