【PHP学习】Yii2框架Gii模块使用

共 1341字,需浏览 3分钟

 ·

2022-07-31 03:34

开启Gii模块

Yii2中使用一个模块通常需要到config文件夹下的web.php下去配置,如下图我们就可以看到Gii模块的使用只有在YIIENVDEV这个变量为Ture时才会被启用。

Gii的模块类的路径为 yii\gii\Module

6662e080f127c6fb276a8b31353a89b3.webp

那么我们在什么地方可以开启这个Gii模块呢?答案:应用的入口文件 web\index.php,在index.php中我们可以看见如下代码:

fde8cbe3c304b4a46050efa1a75193d4.webp

  1. defined('YII_ENV')or define('YII_ENV','dev');// 这行代码就可以使得YII_ENV_DEV为True

【注意】如果Yii2部署到服务器上,远程开发时,会导致远程机访问服务器上的Gii失败,这个时候我们可以将远程机的ip地址设置为Gii的白名单里,我们可以通过 config\web.php进行配置。

  1. $config['modules']['gii']=[

  2. 'class'=>'yii\gii\Module',

  3. // uncomment the following to add your IP if you are not connecting from localhost.

  4. 'allowedIPs'=>['127.0.0.1','xxx.xxx.xxx.xxx'],// 白名单,数组内部的均可以访问

  5. ];

访问Gii模块

如果你已开启上述配置,那么你可以通过下面的地址访问Gii模块

  1. http://hostname/index.php?r=gii // hostname 为你的ip地址或者域名,如果为本地开发可以填写为localhost或者127.0.0.1

Gii模块页面效果图

8d55b1d322b633635060f69ec9327b38.webp

Gii模块使用

前置要求

已经在 config\db.php中配置完数据库信息。

db.php文件

  1. <?php


  2. return[

  3. 'class'=>'yii\db\Connection',

  4. 'dsn'=>'mysql:host=localhost;dbname=yii2basic',// host:数据库连接地址;dbname数据库名称

  5. 'username'=>'root',// 数据库登录名称

  6. 'password'=>'',// 数据库密码

  7. 'charset'=>'utf8',// 编码


  8. // Schema cache options (for production environment)

  9. //'enableSchemaCache' => true,

  10. //'schemaCacheDuration' => 60,

  11. //'schemaCache' => 'cache',

  12. ];

数据库表转为模型(Models)

选中Model Generator下的start按钮,开始生成模型。

0136b7a6e17b479f40123e71549b33b1.webp

点击进入模型生成页面

03298d2c1f217c7c23dc3ed8bde7fe33.webp

填写好要转化的数据库表名称以及表对应的模型名称即可876ab026a3fe85697b6bab74748cb34b.webp

33df47ee1030a87d804672f5301b128e.webp

点击预览后

ab2d7bde04e4eb1d9fa9c2519a96b557.webp

点击生成后

4ac5c85de8d12e5f9d328217947b289f.webp

检查文件是否生成

346e809fb10a4efa08384ed368990bab.webp

生成单表的Crud代码

选择

09c6abee0dab2378976004dc9ef738ea.webp

点击预览

38bed3f0bca09027c447cd7a8540c212.webp

点击生成f35fda4861de10d707344ae36ce5e640.webp

生成文件成功

107f3b3f274c06045325dadb81d1c391.webp

运行crud代码

访问 http://localhost:9999/index.php?r=courses/index

列表信息

5b677cf4c118842bbfe137c20e2d35cc.webp

模糊查询

fcf82ba484415e2e17a26d9d51fc23e6.webp

编辑信息

540d353bedeea433413db0af5e7f2778.webp

查看信息

36af24e8cc6e4195b871f89894e401a1.webp

删除信息

d83b106f00dfc7d515878bfef0911f11.webp

添加信息

0bed0518d3ccc6ded3148cc9cc65f2cc.webp


浏览 32
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐