hyperf OR Laravel创建Model命令

由于数据库表太多不想一个个创建基础的Model模板,所以就写了这个东东! 好了直接上代码把!

Hyperf

<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Command;

use Hyperf\Command\Annotation\Command;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\DbConnection\Db;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Input\InputArgument;

/**
 * @Command
 */
#[Command]
class CreateModelCommand extends HyperfCommand
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var \Hyperf\Contract\ConfigInterface
     */
    protected $config;

    /**
     * @var string
     */
    protected $database;

    public function __construct(ContainerInterface $container, \Hyperf\Contract\ConfigInterface $config)
    {
        $this->container = $container;
        $this->config = $config;
        $this->database = $this->config->get('databases.default.database');

        parent::__construct('create:model');
    }

    public function configure()
    {
        parent::configure();
        $this->setDescription('创建Model');
        $this->addArgument('table_name', InputArgument::OPTIONAL, 'model名称', '');
        $this->addArgument('prefix', InputArgument::OPTIONAL, 'model名称', 'f_');
    }

    public function handle()
    {
        $table = $this->input->getArgument('table_name');
        $table_prefix = $this->input->getArgument('prefix');
        if ($table === '') {
            $this->output->error('参数错误');
            return;
        }

        if ($table === 'all') {
            // 所有表名称
            $tables = Db::select('show tables;');
            foreach ($tables as $table) {
                foreach ($table as $n => $t) {
                    $this->createModel($t, $table_prefix ?: 'f_');
                    break;
                }
            }
        } elseif ($table) {
            $this->createModel($table, $table_prefix ?: 'f_');
        }
        $this->output->text('大功告成');
    }

    private function createModel(string $table, string $prefix): void
    {
        $tableName = str_replace($prefix, '', $table);
        $tableName = explode('_', $tableName);
        $modelName = array_map(function ($value) {
            return ucfirst($value);
        }, $tableName);
        $modelName = implode('', $modelName) . 'Model';
        $fileName = BASE_PATH . '/app/Model/' . $modelName . '.php';
        if (is_file($fileName)) {
            return;
        }
        $classDesc = "/**
 * Class {$modelName}.\n";
        $tableInfo = DB::select("select table_name,table_comment from information_schema.tables  where table_schema = '{$this->database}' and table_name ='{$table}'");
        if (isset($tableInfo[0]->TABLE_COMMENT)) {
            $classDesc .= ' * ' . $tableInfo[0]->TABLE_COMMENT . ".\n";
        }
        $tableFieldInfo = DB::select('show full columns from ' . $table);
        $pk = 'id';

        foreach ($tableFieldInfo as $fieldInfo) {
            if ($fieldInfo->Key === 'PRI') {
                $pk = $fieldInfo->Field;
            }
            if (strpos($fieldInfo->Type, 'int') !== false) {
                $classDesc .= ' * @property int $' . "{$fieldInfo->Field}";
            } else {
                $classDesc .= ' * @property string $' . "{$fieldInfo->Field}";
            }
            if (! empty($fieldInfo->Comment)) {
                $classDesc .= ' ' . $fieldInfo->Comment;
            }
            $classDesc .= "\n";
        }
        $classDesc .= ' */';

        ! is_file($fileName) && file_put_contents($fileName, $this->formatModelString($modelName, $pk, $table, $classDesc));
    }

    private function formatModelString(string $modelName, string $pk, string $table, string $classDesc): string
    {
        $content = '<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Model;

' . $classDesc . '
class {{__MODEL_NAME__}} extends Model
{
    /**
     * 指示是否自动维护时间戳.
     *
     * @var bool
     */
    public $timestamps = false;

    /**
     * 重定义主键.
     *
     * @var string
     */
    protected $primaryKey = \'{{__PK__}}\';

    /**
     * 与模型关联的表名.
     *
     * @var string
     */
    protected $table = \'{{__TABLE_NAME__}}\';
}';
        return str_replace(
            ['{{__MODEL_NAME__}}', '{{__PK__}}', '{{__TABLE_NAME__}}'],
            [$modelName, $pk, $table],
            $content
        );
    }
}

Laravel

<?php
declare(strict_types=1);

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class CreateModelCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'create:model {table_name}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '创建Model';

    /**
     * @var string
     */
    protected $database;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $this->database = config('databases.connections.mysql.database');
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $table = $this->argument('table_name');
        if ('' === $table) {
            $this->output->error('参数错误');
            return;
        }

        if ('all' === $table) {
            // 所有表名称
            $tables = DB::select('show tables;');
            foreach ($tables as $table) {
                foreach ($table as $n => $t) {
                    $this->createModel($t);
                    break;
                }
            }
        } else if ($table) {
            $this->createModel($table);
        }
        $this->output->text('大功告成');
    }

    private function createModel(string $table): void
    {
        // f_为表前缀 改成自己的
        $tableName = str_replace('f_', '', $table);
        $tableName = explode('_', $tableName);
        $modelName = array_map(function ($value) {
            return ucfirst($value);
        }, $tableName);
        $modelName = implode('', $modelName) . 'Model';
        // Model存放目录可以自行修改
        $fileName = app_path('/Models/') . $modelName . '.php';
        if (is_file($fileName)) {
            return;
        }
        $classDesc = "/**
 * Class {$modelName}.\n";
        $tableInfo = DB::select("select table_name,table_comment from information_schema.tables  where table_schema = '{$this->database}' and table_name ='{$table}'");
        if (isset($tableInfo[0]->TABLE_COMMENT)) {
            $classDesc .= ' * ' . $tableInfo[0]->TABLE_COMMENT . ".\n";
        }
        $tableFieldInfo = DB::select('show full columns from ' . $table);

        $pk = 'id';
        foreach ($tableFieldInfo as $fieldInfo) {
            if ($fieldInfo->Key === 'PRI') {
                $pk = $fieldInfo->Field;
            }
            if (strpos($fieldInfo->Type, 'int') !== false) {
                $classDesc .= ' * @property int $' . "{$fieldInfo->Field}";
            } else {
                $classDesc .= ' * @property string $' . "{$fieldInfo->Field}";
            }
            if (!empty($fieldInfo->Comment)) {
                $classDesc .= ' ' . $fieldInfo->Comment;
            }
            $classDesc .= "\n";
        }
        $classDesc .= ' */';
        !is_file($fileName) && file_put_contents($fileName, $this->formatModelString($modelName, $pk, $table, $classDesc));
    }


    private function formatModelString(string $modelName, string $pk, string $table, string $classDesc): string
    {
        $content = '<?php

declare(strict_types=1);

namespace App\Models;

use App\Models\BaseModel;

' . $classDesc . '
class {{__MODEL_NAME__}} extends BaseModel
{
    /**
     * 重定义主键
     *
     * @var string
     */
    protected $primaryKey = \'{{__PK__}}\';

    /**
     * 与模型关联的表名
     *
     * @var string
     */
    protected $table = \'{{__TABLE_NAME__}}\';

    /**
     * 指示是否自动维护时间戳
     *
     * @var bool
     */
    public $timestamps = false;
}';
        return str_replace(['{{__MODEL_NAME__}}', '{{__PK__}}', '{{__TABLE_NAME__}}'],
            [$modelName, $pk, $table], $content);
    }
}

LW放下的博客
请先登录后发表评论
  • latest comments
  • 总共0条评论