您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
7-5 gii工具之控制器生成器
发布时间:2023-05-13 23:29:41编辑:雪饮阅读()
-
控制器生成器的相关概念
继续上篇,这次咱们看到gii上次那个工具界面左侧的Controller Generator,进入后Controller Generator是用来生成控制器的生成器。
这里的Controller Class是需要提供命名空间路径如:
app\controllers\TestController
Action IDs是配置该控制器下面的action的也即就是方法
然后默认会有一个index的方法
如果想要有多个action,则可以用空格分隔,例如这里Action IDs我的最终值配置如:
index index2 index3
View Path一般的是不用配置的,应该是以控制器名(不含Controller)为目录名,如这里生成的路径应如:
D:\phpstudy_pro\WWW\www.xyyii.com\basic\views\test
Base Class大概就是说生成的控制器所extends的父级类
Code Template是代码模板,就是说从这个控制器生成器生成的控制器应该是怎样的,至少的一个骨架模板,当然同样的也有对应的视图模板,文字描述起来很苍白。比如我这里默认使用的如
D:\phpstudy_pro\WWW\www.xyyii.com\basic\vendor\yiisoft\yii2-gii\generators\controller\default
这个路径中的模板中的controller.php是一个控制器模板:
<?php
/**
* This is the template for generating a controller class file.
*/
use yii\helpers\Inflector;
use yii\helpers\StringHelper;
/* @var $this yii\web\View */
/* @var $generator yii\gii\generators\controller\Generator */
echo "<?php\n";
?>
namespace <?= $generator->getControllerNamespace() ?>;
class <?= StringHelper::basename($generator->controllerClass) ?> extends <?= '\\' . trim($generator->baseClass, '\\') . "\n" ?>
{
<?php foreach ($generator->getActionIDs() as $action): ?>
public function action<?= Inflector::id2camel($action) ?>()
{
return $this->render('<?= $action ?>');
}
<?php endforeach; ?>
}
同路径下的view.php是视图模板如:
<?php
/**
* This is the template for generating an action view file.
*/
/* @var $this yii\web\View */
/* @var $generator yii\gii\generators\controller\Generator */
/* @var $action string the action ID */
echo "<?php\n";
?>
/* @var $this yii\web\View */
<?= "?>" ?>
<h1><?= $generator->getControllerID() . '/' . $action ?></h1>
<p>
You may change the content of this page by modifying
the file <code><?= '<?=' ?> __FILE__; ?></code>.
</p>
使用控制器生成器生成一个控制器
前面的都配置好后,最后和之前使用模型生成器差不多,在出现Generate按钮时候点击该按钮即可生成。
最后咱们生成的控制器如
D:\phpstudy_pro\WWW\www.xyyii.com\basic\controllers\TestController.php
<?php
namespace app\controllers;
class TestController extends \yii\web\Controller
{
public function actionIndex()
{
return $this->render('index');
}
public function actionIndex2()
{
return $this->render('index2');
}
public function actionIndex3()
{
return $this->render('index3');
}
}
对应的视图可以看到有3个:
D:\phpstudy_pro\WWW\www.xyyii.com\basic\views\test\index.php:
<?php /* @var $this yii\web\View */ ?> <h1>test/index</h1> <p> You may change the content of this page by modifying the file <code><?= __FILE__; ?></code>. </p>D:\phpstudy_pro\WWW\www.xyyii.com\basic\views\test\index2.php:
<?php /* @var $this yii\web\View */ ?> <h1>test/index2</h1> <p> You may change the content of this page by modifying the file <code><?= __FILE__; ?></code>. </p>D:\phpstudy_pro\WWW\www.xyyii.com\basic\views\test\index3.php:
<?php /* @var $this yii\web\View */ ?> <h1>test/index3</h1> <p> You may change the content of this page by modifying the file <code><?= __FILE__; ?></code>. </p>
关键字词:控制器,生成器