Yii 生成没有 Gii 的模型

2022-01-04 00:00:00 model frameworks php yii gii

我需要在不使用 Gii 的情况下生成模型文件.Yii有什么命令吗?

I need to generate a model file without the use of Gii. Are there any command Yii?

$table = "myTable";
Yii::app()->generateModel($table); // ?

推荐答案

也许官方已经弃用了,你可以用 Yii 命令行工具

Perhaps is officially deprecated, you can generate code with Yii Command Line Tools

我已经用 Yii 1.1.17 测试过了.

I have tested it with Yii 1.1.17.

首先你需要在 protected/commands 上创建一个新文件,例如 NewmodelCommand.php 创建一个新的 yii 命令.我们需要避免使用shell交互工具,在控制器、模型等我们的代码中直接调用命令.为了得到它,我们继承了Yii核心类ModelCommand.这个类最初强迫人们在交互式 shell 上输入.

First you need to create a new file on protected/commands called for example NewmodelCommand.php to create a new yii command. We need to avoid to use shell interactive tool and call command directly from our code in controllers, models, etc. To get it, we inherit Yii core class ModelCommand. This class originally force person to type on interactive shell.

<?php

Yii::import('system.cli.commands.shell.ModelCommand');


class NewmodelCommand extends ModelCommand
{

}

仅此而已.您可以将 CLI 中的命令测试到您的操作系统中.在 Linux 中,打开终端并转到 /protected/ 目录并键入:

That is all. You can test command from CLI into your operating system. In Linux, open your terminal and go to /protected/ directory and type:

./yiic

您将看到如下内容:

...
The following commands are available:
 - message
 - migrate
 - newmodel
 - shell
 - webapp
...

稍微玩一下.再次输入:

Play a little with it. Type again:

./yiic newmodel

您将看到所有命令帮助和文档.

And you will see all command help and documentation.

要使用此命令生成模型,您至少需要 model_name 作为第一个参数.命令将使用与数据库表名相同的模型名:

To generate a model with this command you need at least model_name as first parameter. Command will use same model name as database table name:

./yiic newmodel MyNewModel

如果您有不同的模型和数据库名称:

If you have different model and database name:

./yiic newmodel MyNewModel tbl_new_model

如果您在使用 yiic、定位/连接数据库等方面遇到问题,请确保在 protected/config/console.php 和 查看所有关于 Yii 控制台应用程序的官方文档.

If you have troubles using yiic, locating/connecting your db, etc, make sure to setup properly your console environment on protected/config/console.php and check all official docs about Yii console applications.

最后在您的代码中,您可以根据需要使用您的命令:

Finally in your code you can use your command as you want:

$path = '/full/path/to/protected';
$new_model_name = 'MyNewModel';
shell_exec( $path . "/./yiic newmodel $new_model_name" );

相关文章