hyperf OR Laravel创建Model命令

2020-03-20 16:12:22

由于数据库表太多不想一个个创建基础的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 AppCommand;

use HyperfCommandAnnotationCommand;
use HyperfCommandCommand as HyperfCommand;
use HyperfDbConnectionDb;
use PsrContainerContainerInterface;
use SymfonyComponentConsoleInputInputArgument;

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

    /**
     * @var HyperfContractConfigInterface
     */
    protected $config;

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

    public function __construct(ContainerInterface $container, HyperfContractConfigInterface $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}.
";
        $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 . ".
";
        }
        $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 .= "
";
        }
        $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 AppModel;

' . $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 AppConsoleCommands;

use IlluminateConsoleCommand;
use IlluminateSupportFacadesDB;

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}.
";
        $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 . ".
";
        }
        $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 .= "
";
        }
        $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 AppModels;

use AppModelsBaseModel;

' . $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);
    }
}

本文由"putyy"原创,转载无需和我联系,但请注明来自putyy
您的浏览器不支持canvas标签,请您更换浏览器