Gii可以帮助我们生成代码,减少编写重复代码。

访问:http://localhost/Yii/basic/web/index.php?r=gii可以使用gii功能。

2017101514863r.png

Model

This generator generates an ActiveRecord class for the specified database table.

2017101589514Model-Generator.png

Gii会根据数据库表生成对应的代码(举例):

<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "test2".
 *
 * @property integer $id
 * @property string $title
 */
class TestGii extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'test2';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title'], 'string', 'max' => 20],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',  
            'title' => 'Title', //如果生成时勾选`Generate Labels from DB Comments`,默认以字段名为key ,以字段的注释为name。 没有注释则大写
        ];
    }
}

可以对数据进行校验:

public function  actionTest(){
   $test = new TestGii();
   $test-> title = 44;
   //'title' => 'Title',
   $test->save();
   //获取错误(以title过长举例)
   //Array ( [title] => Array ( [0] => Title should contain at most 20 characters. ) )
   //获取错误(以title = 数字)
   //Array ( [title] => Array ( [0] => Title must be a string. ) )
   print_r($test->getErrors()); //
}

GRUD

Controller

2017101557166Controller-Generator.png

MyTestController为例,访问:http://localhost/Yii/basic/web/index.php?r=my-test可以看到效果

(名字如何解析的,看这里https://github.com/yiisoft/yii2/blob/master/framework/base/Module.php#L560)

Form

Module

Extension