最新消息: 新版网站上线了!!!

yii2 Gii 代码生成器

Gii 代码生成器 

Yii 包含一个名为 Gii 的简易代码生成器,可以用来快速构建常用的原型代码以及完整的控制器CRUD操作。

+

安装和配置 

Gii 是 Yii 的一个官方扩展。推荐的安装方法是使用 composer.

执行如下命令:

php composer.phar require --prefer-dist yiisoft/yii2-gii "*"

或者你可以把如下代码添加到 composer.json 文件中的 require 部分:

"yiisoft/yii2-gii": "*"

Gii 安装好后,你可以在配置文件添加如下代码来启用它:

return [
    'bootstrap' => ['gii'],
    'modules' => [
        'gii' => 'yii\gii\Module',
        // ...
    ],
    // ...
];

然后可以通过下面的URL来访问:

http://localhost/path/to/index.php?r=gii

如果启用了pretty URL,你可以使用如下URL:

http://localhost/path/to/index.php/gii

注意:如果你通过IP地址而不是host名称来访问gii,缺省情况下访问将被拒绝。为了避免这个情况,可以把想要被允许访问的IP地址添加到配置中:

'gii' => [
    'class' => 'yii\gii\Module',
    'allowedIPs' => ['127.0.0.1''::1''192.168.0.*''192.168.178.20'// adjust this to your needs
],

基础应用程序 

基础应用程序模板的配置结构有点不一样,Gii 应该配置在文件 config/web.php 中:

// ...
if (YII_ENV_DEV) {
    // configuration adjustments for 'dev' environment
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = 'yii\debug\Module';

    $config['bootstrap'][] = 'gii';
    $config['modules']['gii'] = 'yii\gii\Module'// <--- here
}

相应的IP地址配置为:

if (YII_ENV_DEV) {
    // configuration adjustments for 'dev' environment
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = 'yii\debug\Module';

    $config['bootstrap'][] = 'gii';
    $config['modules']['gii'] = [
        'class' => 'yii\gii\Module',
        'allowedIPs' => ['127.0.0.1''::1''192.168.0.*''192.168.178.20'],
    ];
}
+

如何使用 

当你打开Gii时,首先看到的入口页面让你选择一个生成器:

Gii entry page

缺省情况下有如下可用的生成器:

  • Model Generator - This generator generates an ActiveRecord class for the specified database table.
  • CRUD Generator - This generator generates a controller and views that implement CRUD (Create, Read, Update, Delete) operations for the specified data model.
  • Controller Generator - This generator helps you to quickly generate a new controller class, one or several controller actions and their corresponding views.
  • Form Generator - This generator generates a view script file that displays a form to collect input for the specified model class.
  • Module Generator - This generator helps you to generate the skeleton code needed by a Yii module.
  • Extension Generator - This generator helps you to generate the files needed by a Yii extension.

点击相应生成器下方的 “Start” 按钮后,你将看到该生成器的配置表单,根据你的实际需求填写表单信息,并点击 "Preview" 按钮来预览将要生成的代码:

Gii preview

点击文件名,你可以预览将生成的该文件的代码。如果文件已经存在,gii 将显示一个代码差异视图,这样你可以决定哪些文件要被覆盖。

Tip: When using the Model Generator to update models after database change, you can copy the code from gii preview and merge the changes with your own code. You can use IDE features like PHPStorms compare with clipboard for this, which allows you to merge in relevant changes and leave out others that may revert your own code.

在你审阅完代码并选择了想要生成的文件后,你可以点击 "Generate" 按钮来创建这些文件。如果遇到错误,请检查文件路径的访问权限。

Note: The code generated by gii is only a template that has to be adjusted to your needs. It is there to help you create new things quickly but it is not something that creates ready to use code. We often see people using the models generated by gii without change and just extend them to adjust some parts of it. This is not how it is meant to be used. Code generated by gii may be incomplete or incorrect and has to be changed to fit your needs before you can use it.

+

自定义模板 

Every generator has a form field Code Template that lets you choose a template to use for code generation. By default gii only provides one templatedefault but you can create your own templates that are adjusted to your needs.

If you open a folder @app\vendor\yiisoft\yii2-gii\generators, you'll see six folders of generators. ` + controller - crud

+ default
  • extension
  • form
  • model
  • module
    This is name generator. If you open any of these folders, you can see the folder `default`. This folder is name of the template.
    

Copy folder @app\vendor\yiisoft\yii2-gii\generators\crud\default to another location, for example @app\myTemplates\crud\. Now open this folder and modify any template to fit your desires, for example, add errorSummary in views\_form.php:

<?php
//...
<div class="<?= Inflector::camel2id(StringHelper::basename($generator->modelClass)) ?>-form">

    <?= "<?php " ?>$form = ActiveForm::begin(); ?>
    <?= "<?=" ?> $form->errorSummary($model) ?> <!-- ADDED HERE -->
    <?php foreach ($safeAttributes as $attribute) {
        echo "    <?= " $generator->generateActiveField($attribute) . " ?>\n\n";
    } ?>
//..

Now you need to tell GII about our template.The setting is made in the config file:

// config/web.php for basic app
// ...
if (YII_ENV_DEV) {    
    $config['modules']['gii'] = [
        'class' => 'yii\gii\Module',      
        'allowedIPs' => ['127.0.0.1''::1''192.168.0.*''192.168.178.20'],  
        'generators' => [ //here
            'crud' => [ //name generator
                'class' => 'yii\gii\generators\crud\Generator'//class generator
                'templates' => [ //setting for out templates
                    'myCrud' => '@app\myTemplates\crud\default'//name template => path to template
                ]
            ]
        ],
    ];
}

Open the CRUD generator and you will see that in the field Code Template of form appeared own template .

+

自定义代码生成器 

Open the folder of any generator and you will see two files form.php and Generator.php. One is the form, the second is the class generator. For create your own generator, you need to create or override these classes in any folder. Again as in the previous paragraph customize configuration:

//config/web.php for basic app
//..
if (YII_ENV_DEV) {    
    $config['modules']['gii'] = [
        'class' => 'yii\gii\Module',      
        'allowedIPs' => ['127.0.0.1''::1''192.168.0.*''192.168.178.20'],  
         'generators' => [
            'myCrud' => [
                'class' => 'app\myTemplates\crud\Generator',
                'templates' => [
                    'my' => '@app/myTemplates/crud/default',
                ]
            ]
        ],
    ];
}
// @app/myTemplates/crud/Generator.php
<?php
namespace app\myTemplates\crud;

class Generator extends \yii\gii\Generator
{
    public function getName()
    {
        return 'MY CRUD Generator';
    }

    public function getDescription()
    {
        return 'My crud generator. The same as a native, but he is mine...';
    }
    
    // ...
}

Open Gii Module and you will see a new generator appears in it.

+

转载请注明:谷谷点程序 » yii2 Gii 代码生成器