Yii2 命令行實現(xiàn)數(shù)據(jù)庫表結(jié)構(gòu)文檔自動生成

因為要寫關(guān)于數(shù)據(jù)庫表說明的文檔,需要有表結(jié)構(gòu),如果一個個表去建表格,然后在復(fù)制每個字段進(jìn)去,那就太沒效率了。其實程序很簡單,用程序獲取數(shù)據(jù)庫Schema,再寫入到markdown文件(文件格式md)里就可以了。因為項目是基于 Yii2 框架,所以用 Yii2 的命令工具來實現(xiàn)。大概的效果圖如下:

<?php

namespace console\controllers;

use Yii;
use yii\console\Controller;

/**
 * 數(shù)據(jù)庫表結(jié)構(gòu)文檔自動生成工具
 * Class TableSchemaController
 * @package console\controllers
 * @author wuzhc <wuzhc2016@163.com>
 * @since 2018-01-18
 */
class TableSchemaController extends Controller
{
    /**
     * 數(shù)據(jù)庫表生成
     */
    public function actionCreate()
    {
        global $argv;

        if (!$argv[2] || strcasecmp($argv[2], 'help') === 0) {
            echo "Usage: ./yii table-schema/create [all|tablename] [filename]\n";
            exit;
        }

        $db = Yii::$app->db;
        $allTables = $db->getSchema()->getTableNames();

        if ('all' === $argv[2]) {
            $tables = array_diff($allTables, $this->filterTables());
        } else {
            if (!in_array($argv[2], $allTables)) {
                echo sprintf("%s isn't exist \n", $argv[2]);
                exit;
            }
            $tables = (array)$argv[2];
        }

        // 當(dāng)前數(shù)據(jù)庫沒有表
        if (count(array_filter($tables)) == 0) {
            echo "Database has not table \n";
        }

        $root = dirname(dirname(dirname(__FILE__)));
        $filename = $argv[3] ? $argv[3] : '/docs/note/數(shù)據(jù)庫設(shè)計及字典說明.md';
        $filePath = $root . $filename;

        $fp = fopen($filePath, 'a+');
        if (!$fp) {
            echo "Open file failed \n";
        }

        foreach ($tables as $table) {
            $schema = $db->getTableSchema($table, true);
            if (!$schema->columns) {
                continue;
            }

            fwrite($fp, "#### $schema->name 表 \n");

            // 表頭
            $header = "| 字段名 | 類型 | 說明 | \n";
            $header .= "|:--------:|:---------:|:-------:| \n";
            fwrite($fp, $header);

            // 字段
            $row = '';

            foreach ($schema->columns as $col => $obj) {
                $comment = $obj->isPrimaryKey ? '主鍵' : $obj->comment;
                $row .= "| $obj->name | $obj->dbType | $comment | \n";
            }

            fwrite($fp, $row);
            fwrite($fp, "\r\n\r\n");

            echo "$schema->name successfully \n";
        }

        fclose($fp);
    }

    /**
     * 需要過濾的表(不希望生成文檔的表)
     * @return array
     */
    protected function filterTables()
    {
        $filterTables = [
            'tbmigration',
            'tbAuthAssignment',
            'tbAuthItemChild',
            'tbAuthRule',
            'tbItemTable'
        ];

        return $filterTables;
    }

    /**
     * 所有表
     * @return \string[]
     */
    protected function allTables()
    {
        return Yii::$app->db->getSchema()->getTableNames();
    }

    /**
     * 清空
     */
    public function actionClear()
    {
        global $argv;

        if (!$argv[2] || strcasecmp($argv[2], 'help') === 0) {
            echo "Usage: ./yii table-schema/clear [filename]\n";
            exit;
        }

        $root = dirname(dirname(dirname(__FILE__)));
        $filePath = $argv[2] ? $argv[2] : '/docs/note/數(shù)據(jù)庫設(shè)計及字典說明.md';
        $filePath = $root . $filePath;

        if (!is_file($filePath)) {
            echo "$filePath isn't exists \n";
            exit;
        }

        $fp = fopen($filePath, 'w');
        if (!$fp) {
            echo "Open file failed \n";
        }

        fwrite($fp, '');
        fclose($fp);

        echo "Clear successfully \n";
    }
}

執(zhí)行命令:

./yii table-schema/create [all|tablename] [filename] 
# 例如生成所有表到test.md文件 
./yii table-schema/create all test.md
# 生成user表到test.md文件
./yii table-schema/create user test.md
# 清空文檔
./yii table-schema/clear [filename]

原文:https://segmentfault.com/a/1190000012895446

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容