zoukankan      html  css  js  c++  java
  • 命令生成所有数据库表模型以及 CRUD

    将下列代码写到文件复制到项目 consolecontroller 目录下:

    <?php
    namespace consolecontrollers;
    use Yii;
    use yiiconsoleController;
    use yiigiiCodeFile;
    use yiihelpersConsole;
    use yiigiigeneratorsmodelGenerator;
    use yiigiigeneratorscrudGenerator as CrudGenerator;
    class AutoGiiController extends Controller
    {
        /**
         * 不创建模型的表
         * @var array
         */
        public $blackModelTables = [
            'auth_assignment',
            'auth_item',
            'auth_item_child',
            'auth_rule',
            'banner',
            'menu',
            'member',
            'user',
            'miniProgram',
            'region',
        ];
        /**
         * 不创建的crud的table 黑名单
         * @var array
         */
        public $blackCrudTables = [
            'auth_assignment',
            'auth_item',
            'auth_item_child',
            'auth_rule',
            'banner',
            'menu',
            'member',
            'user',
            'miniProgram',
            'region',
        ];
        /**
         * 生成所有 model
         * actionModel
         * @throws yiiaseNotSupportedException
         */
        public function actionModel()
        {
            $tables = Yii::$app->db->getSchema()->tableNames;
            foreach ( $tables as $table ) {
                if(in_array($table,$this->blackModelTables)){
                    continue;
                }
                try {
                    $generator = new Generator();
                    //配置模板
                    $generator->templates = [
                        'Absolute' => Yii::getAlias('@backend/components/giiTemplate/Absolute/model/default')
                    ];
                    $generator->baseClass  = 'commonmodelsBaseActiveRecord'; //父类文件
                    $generator->template   = 'Absolute';                        //模板
                    $generator->queryNs    = 'commonmodels';                   //命名空间
                    $generator->ns         = 'commonmodels';                   //命名空间
                    $generator->modelClass = $this->formatTableName($table);    //格式化类名
                    $generator->tableName  = $table;
                    $files = $generator->generate();
                    $n     = count($files);
                    if ( $n === 0 ) {
                        $this->stdout("
     {$table} 没有文件要生成.", Console::FG_RED);
                        continue;
                    }
                    /** @var CodeFile $file */
                    foreach ( $files as $file ) {
                        $file->getRelativePath();
                        $this->writeContentFile($file->path, $file->content);
                    }
                } catch ( Exception $e ) {
                    $this->stdout("
     {$table} 生成失败.". "
    ", Console::FG_RED);
                    $this->stdout("
    " . $e->getTraceAsString() . "
    ", Console::FG_RED);
                    $this->stdout("
    " . $e->getMessage() . "
    ", Console::FG_RED);
                    break;
                }
            }
        }
        /**
         * 格式化表名
         * formatTableName
         * @param $tableName
         * @return mixed
         */
        protected function formatTableName($tableName)
        {
            $tableName = str_replace('_', ' ', $tableName);
            $tableName = str_replace('-', ' ', $tableName);
            $tableName = ucwords($tableName);
            return str_replace(' ', '', $tableName);
        }
        /**
         * 生成所有 crud
         * actionCrud
         * @throws yiiaseNotSupportedException
         */
        public function actionCrud()
        {
            $tables = Yii::$app->db->getSchema()->tableNames;
            foreach ( $tables as $table ) {
                if(in_array($table,$this->blackCrudTables)){
                    continue;
                }
                try {
                    $generator = new CrudGenerator();
                    $generator->templates = [
                        'Absolute' => Yii::getAlias('@backend/components/giiTemplate/Absolute/crud/default'),
                    ];
                    $tableName = $this->formatTableName($table);
                    $this->writeModelFile($tableName);
                    $generator->template            = 'Absolute';                                       //模板
                    $generator->modelClass          = "backendmodels\".$tableName;                    //模型类
                    $generator->controllerClass     = "backendcontrollers\".$tableName."Controller";  //控制器名称
                    $generator->viewPath            = $this->formatViewPath($tableName);                //视图路径
                    $generator->baseControllerClass = "backendcontrollers\BackendController";         //父控制器
                    $generator->searchModelClass    = "backendmodelssearch\".$tableName."Search";    //搜索模型名称
                    $files = $generator->generate();
                    $n     = count($files);
                    if ( $n === 0 ) {
                        $this->stdout("
     {$table} 没有文件要生成.", Console::FG_RED);
                        continue;
                    }
                    /** @var CodeFile $file */
                    foreach ( $files as $file ) {
                        $file->getRelativePath();
                        $this->writeContentFile($file->path, $file->content);
                    }
                }catch ( Exception $e ) {
                    $this->stdout("
     {$table} 生成失败.". "
    ", Console::FG_RED);
                    $this->stdout("
    " . $e->getTraceAsString() . "
    ", Console::FG_RED);
                    $this->stdout("
    " . $e->getMessage() . "
    ", Console::FG_RED);
                    break;
                }
            }
        }
        /**
         * 格式视图路径名称
         * formatViewPath
         * @param $tableName
         * @return bool|string
         * @throws Exception
         */
        protected function formatViewPath($tableName)
        {
            $dir = Yii::getAlias("@backend/views/".strtolower(preg_replace('/((?<=[a-z])(?=[A-Z]))/', '-', $tableName)));
            if (!is_dir($dir)) {
                $mask = @umask(0);
                $result = @mkdir($dir, 0777, true);
                @umask($mask);
                if (!$result) {
                    throw  new Exception("Unable to create the directory '$dir'.");
                }
            }
            return $dir;
        }
        /**
         * writeModelFile
         * 复制 父类模型 文件
         * @param $tableName
         * @throws Exception
         */
        protected function writeModelFile($tableName)
        {
            $backendModelFile = Yii::getAlias("@backend/models/".$tableName.".php");
            if(!is_file($backendModelFile)){
                $content = <<<PHP
    <?php
    namespace backendmodels;
    use Yii;
    class {$tableName} extends commonmodels\{$tableName}
    {
    }
    PHP;
                $this->writeContentFile($backendModelFile,$content);
            }
        }
        /**
         * writeContentFile
         * @param $file
         * @param $content
         * @throws Exception
         */
        protected function writeContentFile($file,$content)
        {
            if (@file_put_contents($file, $content) === false) {
                throw  new Exception("写入文件到 '{$file}' 错误.");
            }
            $mask = @umask(0);
            @chmod($file, 0666);
            @umask($mask);
            $this->stdout("
     生成文件 {$file} 成功 
    ", Console::FG_GREEN);
        }
    }
    

      

    执行命令:

    //创建model
    php yii auto-gii/model
    
    //创建crud
    php yii auto-gii/crud
    

      

    创建的model说明:只是在common下生成,并且继承自己重写 yiidbActiveRecord 的父类模型文件 BaseActiveRecord, 创建crud,在backend的model目录写一个模型文件继承 commonmodel 目录下的模型文件。自己使用要根据业务需求更改 没做命令行匹配,改的频率很低,代码都有注释。 效果:

     

  • 相关阅读:
    【java学习笔记】反射基础
    【java学习笔记】线程
    【java学习笔记】Properties
    【java学习笔记】序列化、反序列化
    Java Review (二十六、集合----- Set 集合)
    Java Review (二十五、集合----- Iterator接口)
    Java Review (二十四、集合-----Collection 接口)
    Java Review (二十三、集合-----概述)
    Java Review (二十二、正则表达式)
    Java Review (二十一、基础类库----日期、时间类)
  • 原文地址:https://www.cnblogs.com/echojson/p/10765973.html
Copyright © 2011-2022 走看看