thinkphp 一個模型對應一個數(shù)據(jù)表,所以數(shù)據(jù)表里面字段也是模型的一些屬性,但是因為php是動態(tài)語言,模型里面的屬性并不能直觀的看到,出了數(shù)據(jù)表里面的字段以外的屬性,模型其實還包含了通過getXXXAttr方法定義的屬性,還有關聯(lián)關系定義的屬性比如hasOne,hasMany等等。雖然thinkphp支持了通過訪問數(shù)組的形式訪問模型的屬性,但是還是不直觀,另一個是不知道模型屬性的字段含義,如果手動維護容易遺漏和出錯,所以我基于thinkphp5.1開發(fā)了模型屬性自動生成器。
倉庫地址:https://github.com/xiaobai1993/model_property_helper,支持composer 安裝。
功能介紹
- 基于thinkphp的command命令類,提供基本的交互。
- 自動更新模型的屬性,同時生成注釋。包括數(shù)據(jù)表字段、獲取器定義,關聯(lián)關系定義。
- 支持在同一個目錄下的所有的模型統(tǒng)一更新,也支持單個模型文件更新。
- 根據(jù)數(shù)據(jù)表創(chuàng)建的語句中字段的注釋或者php文件中的注釋,自動為屬性增加注釋信息。
源碼如下
<?php
/**
* Created by PhpStorm.
* User: guodong
* Date: 2020/4/2
* Time: 下午2:35
*/
namespace app\common\command\code;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\Loader;
use think\Model;
class ModelProperty extends Command
{
protected static $tabs = " ";
protected function configure()
{
$this->setName('amp')
->addArgument('model', Argument::OPTIONAL, "模型的名字")
->addOption('override', null, Option::VALUE_OPTIONAL, '是否強制覆蓋')
->setDescription('模型自動增加屬性注釋');
}
protected function execute(Input $input, Output $output)
{
$modelPath = $input->getArgument('model');
$path = APP_PATH . $modelPath;
if (is_dir($path)) {
foreach (scandir($path) as $value) {
if ($value == '.' || $value == '..') {
continue;
}
$filePath = $path . "/" . $value;
if (is_file($filePath)) {
try {
$this->parseSingleFile($filePath);
} catch (\Exception $exception) {
echo $exception->getMessage();
}
} else {
continue;//目錄嵌套暫時不處理
}
}
} elseif (is_file($path)) {
$this->parseSingleFile($path);
} else {
exception("$path 文件不存在");
}
}
public function parseSingleFile($filePath)
{
$fileContent = file_get_contents($filePath);
if (preg_match('/namespace (.*?);/', $fileContent, $spaceMatch)) {
$spaceName = $spaceMatch[1];
if (preg_match('/class (.*?) extends .*?Model/', $fileContent, $classMatch)) {
$className = $classMatch[1];
$class = $spaceName . "\\" . $className;
if (class_exists($class)) {
$instance = new $class();
if ($instance instanceof Model) {
$comments = [];
$this->parseTableAttr($instance, $comments);
$this->parseClass($instance, $comments);
$classComments = "\n\n/**\n" . implode("\n", $comments) . "\n*/\n\n";
$result = preg_replace('/^([\s\S]*;)([\s\S]*?)(class.*?extends[\s\S]*)$/', "$1$classComments$3", $fileContent);
file_put_contents($filePath, $result);
} else {
exception("$class 不是模型類");
}
} else {
exception("$class 不存在");
}
} else {
exception("未能找到" . basename($filePath) . "類的名字");
}
} else {
exception("未能找到" . basename($filePath) . "類的命名空間");
}
}
/**
* 掃碼數(shù)據(jù)表的屬性
* @param Model $model
* @param $comments
* @return string
*/
protected function parseTableAttr(Model $model, &$comments)
{
$tableSql = $model->query("show create table " . $model->getTable())[0]['Create Table'];
preg_match_all("#`(.*?)`(.*?) COMMENT\s*'(.*?)',#", $tableSql, $matches);
$fields = $matches[1];
$cts = $matches[3];
if (preg_match('/COMMENT=\'(.*?)\'$/', $tableSql, $m2)) {
$comments[] = " * " . $m2[1];
}
for ($i = 0; $i < count($matches[0]); $i++) {
$comments[] = " * @property $" . $fields[$i] . self::$tabs . $cts[$i];
}
}
/**
* 獲取模型文件的方法
* @param $model
* @param $comments
*/
protected function parseClass(Model $model, &$comments)
{
$classReflect = new \ReflectionClass($model);
$tableFields = $model->getTableFields();
$filePath = $classReflect->getFileName();
if ($filePath) {
$content = file_get_contents($filePath);
} else {
$content = "";
}
$methods = $classReflect->getMethods(\ReflectionMethod::IS_PUBLIC);
foreach ($methods as $method) {
if ($method->isAbstract() || $method->isStatic()) {
continue;
}
$methodName = $method->getName();
//只查詢本類文件存在的
if ($content && strpos($content, "function " . $methodName)) {
if (preg_match('/get(.*?)Attr/', $methodName, $match)) { //屬性
$propertyName = Loader::parseName($match[1], 0, false);
if (in_array($propertyName, $tableFields)) {
continue;
}
$comments[] = " * @property $" . $propertyName . self::$tabs . $this->getDocTitle($method->getDocComment());
} else {
$startLine = $method->getStartLine();
$endLine = $method->getEndLine();
$methodContent = $this->readFile($filePath, $startLine, $endLine);
if (preg_match('/return.*?->(.*?)\([,]?(.*?)::class,/', $methodContent, $match)) {
$relation = $match[1];
$relationModel = $match[2];
$propertyName = Loader::parseName($methodName, 0, false);
if ($relation == 'hasMany' || $relation == 'belongsToMany') {
$comments[] = " * @property ". $relationModel . "[]" . " $" . $propertyName . self::$tabs . $this->getDocTitle($method->getDocComment());
} else {
$comments[] = " * @property " .$relationModel . " $" . $propertyName . self::$tabs . $this->getDocTitle($method->getDocComment());
}
}
}
} else {
continue;
}
}
}
/**
* 讀文件
* @param $file_name
* @param $start
* @param $end
* @return string
*/
protected function readFile($file_name, $start, $end)
{
$limit = $end - $start;
$f = new \SplFileObject($file_name, 'r');
$f->seek($start);
$ret = "";
for ($i = 0; $i < $limit; $i++) {
$ret .= $f->current();
$f->next();
}
return $ret;
}
/**
* 獲取類或者方法注釋的標題,第一行
* @param $docComment
* @return string
*/
protected function getDocTitle($docComment)
{
if ($docComment !== false) {
$docCommentArr = explode("\n", $docComment);
$comment = trim($docCommentArr[1]);
return trim(substr($comment, strpos($comment, '*') + 1));
}
return '';
}
}
案例測試
# 整個目錄的模型都更新了
php think amp dbase/model/
隨便拿幾個看看

image.png

image.png
可以發(fā)現(xiàn)生成了較為完善的注釋信息,對于關聯(lián)信息也根據(jù)關聯(lián)關系指定是對象還是對象數(shù)組。