简体   繁体   中英

Yii generate model without Gii

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

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

Don't think there is a command. You could create the model, or the command, yourself. Other option would be to make the requests to Gii via curl.

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

I have tested it with Yii 1.1.17.

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
{

}

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

You will see something like this:

...
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.

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

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" );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM