众所周知 Yii 2 是一个非常高效的 PHP 框架 它之所以高效 有部分原因在于 它的模型生成器非常方便 可以帮助我们生成代码 避免了 我们的重复劳作
下面我就将详细的介绍一下 Yii 2 框架中 gii模型生产器 的具体使用方法 来降低大家的代码重复量 从而体会到编程过程中思考的乐趣
首先我们需要打开gii工具 打开的方法 非常容易 打开网页即可 输入 http://localhost/yii2/web/gii 便可打开gii工具
效果显示图如下
ps(我使用的是 PATH_INFO 格式输入网址 并隐藏了index.php文件 Yii2初始登录gii的方式应该为 http://localhost/yii2/web/index.php/?r=gii)
我们点进 Model Generator
会看到下面这样的情况
下面我来详细介绍一下 gii模型生成器 各个主要选项的 作用是什么
Table Name
数据表的名称Model Class
我们要生成模型类的名称Use Table Prefix
是否使用表前缀Generate Labels from DB Comments
是否生产数据表各个标签对应的注释下面我们来生产一个表单做实验
如图生产表单
生产的模型类代码如下
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "study_student".
*
* @property string $id
* @property string $s_no
* @property string $s_user
* @property string $s_nation
* @property string $s_sex
* @property string $s_major
* @property string $s_class
* @property string $head
*/
class Student extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'study_student';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['s_no'], 'string', 'max' => 12],
[['s_user'], 'string', 'max' => 50],
[['s_nation', 's_sex'], 'string', 'max' => 5],
[['s_major'], 'string', 'max' => 20],
[['s_class'], 'string', 'max' => 10],
[['head'], 'string', 'max' => 255],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
's_no' => 'S No',
's_user' => 'S User',
's_nation' => 'S Nation',
's_sex' => 'S Sex',
's_major' => 'S Major',
's_class' => 'S Class',
'head' => 'Head',
];
}
}
如果我使用了表前缀并勾选了 Generate Labels from DB Comments 那效果将是这样
生成的代码如下
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "{{%student}}".
*
* @property string $id
* @property string $s_no
* @property string $s_user
* @property string $s_nation
* @property string $s_sex
* @property string $s_major
* @property string $s_class
* @property string $head
*/
class Student extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%student}}';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['s_no'], 'string', 'max' => 12],
[['s_user'], 'string', 'max' => 50],
[['s_nation', 's_sex'], 'string', 'max' => 5],
[['s_major'], 'string', 'max' => 20],
[['s_class'], 'string', 'max' => 10],
[['head'], 'string', 'max' => 255],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => '学生的id',
's_no' => '学生的学号',
's_user' => '学生的名字',
's_nation' => '民族',
's_sex' => '性别',
's_major' => '专业',
's_class' => '班级',
'head' => '头像',
];
}
}