Initial commit

This commit is contained in:
18338781771
2025-05-14 13:19:23 +08:00
commit 1ab607f65a
313 changed files with 27595 additions and 0 deletions
+168
View File
@@ -0,0 +1,168 @@
<?php
namespace app\mzl\generate\actions;
use Symfony\Component\Filesystem\Filesystem;
use app\mzl\common\utils\TableInspector;
class Generate
{
// 表名
protected $name = '';
// 控制器名
protected $convertName = '';
// 模块名
protected $moduleName = '';
// 表前缀
protected $dbPrefix = 'hs_';
public function __construct()
{
//
}
public function doGenerate()
{
$fs = new Filesystem();
// 模板路径
$templateDir = __DIR__ . '/../templates/';
$controllerPath = __DIR__ . "/../../../{$this->moduleName}/controller/{$this->convertName}Controller.php";
$servicePath = __DIR__ . "/../../../{$this->moduleName}/service/{$this->convertName}Service.php";
$modelPath = __DIR__ . "/../../../{$this->moduleName}/model/{$this->convertName}Model.php";
$validatePath = __DIR__ . "/../../../{$this->moduleName}/validate/{$this->convertName}Validator.php";
// // 创建目录(如果不存在)
$fs->mkdir(__DIR__ . "/../../../{$this->moduleName}/controller");
$fs->mkdir(__DIR__ . "/../../../{$this->moduleName}/service");
$fs->mkdir(__DIR__ . "/../../../{$this->moduleName}/model");
$fs->mkdir(__DIR__ . "/../../../{$this->moduleName}/validate");
// // 删除已存在的文件并重新生成
$this->deleteFileIfExists($controllerPath);
$this->deleteFileIfExists($servicePath);
$this->deleteFileIfExists($modelPath);
$this->deleteFileIfExists($validatePath);
// 生成控制器文件
$ControllerStub = $this->generateFile($templateDir, 'ControllerStub.stub', $controllerPath);
// 生成服务类文件
$ServiceStub = $this->generateFile($templateDir, 'ServiceStub.stub', $servicePath);
// 生成模型类文件
$ModelStub = $this->generateFile($templateDir, 'ModelStub.stub', $modelPath);
// 生成验证器类文件
$ValidatorStub = $this->generateFile($templateDir, 'ValidatorStub.stub', $validatePath);
return $ControllerStub . $ServiceStub . $ModelStub . $ValidatorStub . "<info>文件生成成功!</info> <br/>";
}
/**
* 设置字段
*
* @param array $fields 字段数组
*/
public function fillableFields()
{
$tableName = $this->dbPrefix.$this->name;
$fields = TableInspector::getColumnNames($tableName);
$str = '';
foreach ($fields as $key => $val) {
if ($key < (count($fields)-1)) {
$str .= "'{$val}', ";
} else {
$str .= "'{$val}'";
}
}
$fields = trim($str, '"');
return $fields;
}
/**
* 根据模板生成文件
*
* @param string $templateDir 模板目录
* @param string $templateFile 模板文件名
* @param string $outputPath 输出文件路径
*/
protected function generateFile($templateDir, $templateFile, $outputPath)
{
$templatePath = $templateDir . $templateFile;
if (!file_exists($templatePath)) {
echo "<error>模板文件 {$templateFile} 不存在!</error> \n";
return;
}
$content = file_get_contents($templatePath);
$content = str_replace('{{name}}', $this->convertName, $content);
// 填入table名
$content = str_replace('{{table}}', $this->dbPrefix.$this->name, $content);
// 填入module名
$content = str_replace('{{module}}', $this->moduleName, $content);
// 填入字段
$content = str_replace('{{fillableFields}}', $this->fillableFields(), $content);
file_put_contents($outputPath, $content);
return "生成文件: <info>{$outputPath}</info> <br/>";
}
/**
* 如果文件存在,删除它
*
* @param string $path 文件路径
*/
protected function deleteFileIfExists($path)
{
if (file_exists($path)) {
unlink($path);
echo "删除已存在文件: <comment>{$path}</comment> \n";
}
}
/**
* 设置名称
*/
public function setName($name = '')
{
$this->name = $name;
$this->convertName = ucfirst(camelize($name));
}
/**
* 设置模块名称
*/
public function setModule($name = '')
{
$this->moduleName = $name;
}
}
/**
* 下划线转驼峰
* 思路:
* step1.原字符串转小写,原字符串中的分隔符用空格替换,在字符串开头加上分隔符
* step2.将字符串中每个单词的首字母转换为大写,再去空格,去字符串首部附加的分隔符.
*/
function camelize($uncamelized_words, $separator='_') {
$uncamelized_words = $separator . str_replace($separator, " ", strtolower($uncamelized_words));
return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator );
}
/**
* 驼峰命名转下划线命名
* 思路:
* 小写和大写紧挨一起的地方,加上分隔符,然后全部转小写
*/
function uncamelize($camelCaps, $separator='_') {
return strtolower(preg_replace('/([a-z])([A-Z])/', "$1" . $separator . "$2", $camelCaps));
}
@@ -0,0 +1,81 @@
<?php
namespace app\{{module}}\controller;
use support\Request;
use support\Response;
use app\{{module}}\model\{{name}}Model;
use app\{{module}}\service\{{name}}Service;
use app\{{module}}\validate\{{name}}Validator;
use app\mzl\common\controller\BaseController;
class {{name}}Controller extends BaseController
{
/**
* 不需要验证token的接口
* @var array
*/
protected $noNeedJwt = [];
/**
* 验证器
*/
protected mixed $validator = {{name}}Validator::class;
/**
* 返回业务 Service 实例
*/
protected function getService()
{
return new {{name}}Service(new {{name}}Model());
}
/**
* 额外字段处理 (根据场景处理)
* @param array $item
* @param string $scene
* @return array
*/
protected function postProcessItem(array $item, string $scene): array
{
if ($scene === 'default') {
}
return $item;
}
/**
* 参数预处理 (根据场景处理)
* @param Request $request
* @param string $scene
* @return array
*/
protected function prepareParams(Request $request, string $scene): array
{
$params = parent::prepareParams($request, $scene);
if ($scene === 'default') {
}
return $params;
}
/**
* 分页
*
* @param Request $request 请求对象
* @return Response 响应对象
*/
public function index(Request $request, string $scene = 'default'): Response
{
try {
return parent::index($request, $scene);
} catch (\Throwable $th) {
return $this->errorResponse($th->getMessage());
}
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
namespace app\{{module}}\model;
use support\Model;
/**
* {{name}}Model
*/
class {{name}}Model extends Model
{
/**
* The connection name for the model.
*
* @var string|null
*/
protected $connection = 'mysql';
/**
* The table associated with the model.
*
* @var string
*/
protected $table = '{{table}}';
/**
* The primary key associated with the table.
*
* @var string
*/
protected $primaryKey = 'id';
/**
* Indicates if the model should be timestamped.
*
* @var bool
*/
public $timestamps = true;
/**
* 模型的数据字段的保存格式。
*
* @var string
*/
protected $dateFormat = 'U';
/**
* 允许自动填充模型字段
*/
protected $fillable = [{{fillableFields}}];
/**
* 不允许自动填充模型字段
*/
protected $guarded = [];
}
@@ -0,0 +1,59 @@
<?php
namespace app\{{module}}\service;
use app\{{module}}\model\{{name}}Model;
use app\mzl\common\services\BaseService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
class {{name}}Service extends BaseService
{
/**
* 定义模型
*
* @return string
*/
public function getModel(): string
{
return {{name}}Model::class;
}
/**
* 多场景配置
*/
public function queryScenes(): array
{
return [
// 'default' => function ($params) {
// $keyword = $params['keyword'] ?? '';
// return [
// 'filters' => [
// ['field' => '***', 'operator' => '=', 'value' => '***']
// ],
// 'fields' => ['id'],
// 'relations' => [],
// 'custom' => function(Builder $q) use ($keyword) {
// // 示例
// if ($keyword) {
// $q->where(function($q2) use($keyword) {
// $q2->whereHas('***', function($q3) use($keyword) {
// $q3->where('***', 'like', "%{$keyword}%");
// })->orWhereHas('***', function($q4) use($keyword) {
// $q4->where('***', 'like', "%{$keyword}%");
// });
// });
// }
// },
// 'sorts' => [
// ['field' => 'created_at', 'direction' => 'desc']
// ],
// 'pagination' => [
// 'page' => $params['page'] ?? 1,
// 'per_page' => $params['per_page'] ?? 10,
// ]
// ];
// }
];
}
}
@@ -0,0 +1,29 @@
<?php
namespace app\{{module}}\validate;
use think\Validate;
class {{name}}Validator extends Validate
{
// 规则
protected $rule = [
];
// 提示
protected $message = [
];
// 场景
protected $scene = [
'store' => [
],
'update' => [
]
];
}