目录
1. 使用 Gii
2. 扩展 Gii
代码生成器的架构
生成器搜索路径
定制代码模板
创建新的生成器
首页 后端开发 php教程 Yii框架官方指南系列41——专题:自动代码生成

Yii框架官方指南系列41——专题:自动代码生成

Feb 16, 2017 am 09:15 AM

自版本 1.1.2 起, Yii 装备了基于 Web 界面的代码生成工具Gii。 它取代了之前的命令行端的代码生成工具 yiic shell。 在这部分,我们将讲解如何使用 Gii 以及如何扩展 Gii 以增加我们的开发成果。

1. 使用 Gii

Gii 是以模块的方式实现的,它必须在一个已存在的 Yii 应用程序中使用。要使用 Gii,我们首先更改应用程序的配置如下:


return array(
    ......
    'modules'=>array(
        'gii'=>array(
            'class'=>'system.gii.GiiModule',
            'password'=>'在这里填写密码',
            // 'ipFilters'=>array(...IP 列表...),
            // 'newFileMode'=>0666,
            // 'newDirMode'=>0777,
        ),
    ),
);
登录后复制


在上面,我们声明了一个名为 gii 的模块,它的类是 GiiModule。我们也为这个模块设置了一个密码,我们访问 Gii 时会有一个输入框要求填写这个密码。

出于安全考虑,默认情况下只允许本机访问 Gii。若允许其他可信赖的机器访问它,我们需要如上所示配置GiiModule::ipFilters 属性。

因为 Gii 会生成并保存新文件到应用程序中,我们需要确保 Web 服务器进程有权限这样做。上面的GiiModule::newFileMode 和 GiiModule::newDirMode 属性控制如何生成新文件和新目录。

注意: Gii 主要用作一个开发工具。因此,应当只在开发机器上安装它。因为它可以在应用程序中生成新的 PHP 文件,我们应当对安全问题足够重视(例如设置密码,IP 过滤)。

现在可以通过 URL http://www.php.cn/ 访问 Gii 了。这里我们假设http://www.php.cn/ 是访问 Yii 应用程序的 URL。

若 Yii 应用程序使用 path 格式的 URL (查看 URL management),我们可以通过 URL http://www.php.cn/ 访问 Gii。 我们可能需要增加如下 URL 规则到已有的 URL 规则的前面:

'components'=>array(
    ......
    'urlManager'=>array(
        'urlFormat'=>'path',
        'rules'=>array(
            'gii'=>'gii',
            'gii/<controller:\w+>'=>'gii/<controller>',
            'gii/<controller:\w+>/<action:\w+>'=>'gii/<controller>/<action>',
            ...已有的规则...
        ),
    ),
)
登录后复制


Gii 有一些默认的代码生成器。每个代码生成器负责生成特定类型的代码。例如 controller 生成器生成一个 controller 类以及一些 action view 脚本; model 生成器为指定的数据表生成一个 ActiveRecord 类。

使用一个生成器的基本流程如下:

  1. 进入生成器页面;

  2. 填写指定代码生成参数的输入框。例如,使用 Module Generator 创建一个新模块,你需要指定 module ID;

  3. 点击 Preview 按钮预览即将生成的代码。你将看到一个表格中列出了将要生成的文件列表。你可以点击其中任何一个文件来预览代码;

  4. 点击 Generate 按钮生成这些代码文件;

  5. 查看代码生成日志。

2. 扩展 Gii

虽然默认的 Gii 代码生成器可以生成非常强大的代码,然而我们经常想定制它们或者创建一个新的来适应我们的口味和需求。例如,我们想让生成的代码是我们喜欢的风格,或者想让代码支持多种语言。所有这些在 Gii 中都可非常容易地实现。

可以 2 种方式扩展 Gii:定制已存在的代码生成器的代码模板,以及编写新的代码生成器。

代码生成器的架构

一个代码生成器存储在一个目录中,这个目录的名字被认为是生成器的名字。目录通常由如下内容组成:

model/                       the model generator root folder
   ModelCode.php             the code model used to generate code
   ModelGenerator.php        the code generation controller
   views/                    containing view scripts for the generator
      index.php              the default view script
   templates/                containing code template sets
      default/               the 'default' code template set
         model.php           the code template for generating model class code
登录后复制

生成器搜索路径

Gii 在GiiModule::generatorPaths 属性指定的目录中查找可用的生成器。 当需要定制时,我们可以在应用程序的配置文件中做如下配置,


return array(
    'modules'=>array(
        'gii'=>array(
            'class'=>'system.gii.GiiModule',
            'generatorPaths'=>array(
                'application.gii',   // a path alias
            ),
        ),
    ),
);
登录后复制


上面的配置告诉 Gii 在别名是 application.gii 的目录中寻找生成器,以及默认的位置system.gii.generators

在不同的搜索路径有同名的生成器也是可以的。这种情况下,在 GiiModule::generatorPaths 指定目录中先出现的生成器有优先权。

定制代码模板

这是扩展 Gii 最容易最常用的方式。我们使用一个例子来介绍如何定制代码模板。假设我们想要定制由 model 生成器生成的代码。

我们首先创建一个名为 protected/gii/model/templates/compact 的目录。这里的 model 意味着我们将要override 默认的 model 生成器。 templates/compact 意味着我们将增加一个新的代码模板集名为 compact

然后我们在应用程序配置里把 application.gii 增加到 GiiModule::generatorPaths 。如上所示。

现在打开 model 代码生成器页面。点击 Code Template 输入框。我们应当看到一个下拉列表,这个列表包含了我们新建的模板目录 compact。可是,若我们选择此模板生成代码,我们将看到错误。这是因为我们还没有在新的 compact 模板集中放入任何实际的代码模板文件。

复制文件 framework/gii/generators/model/templates/default/model.php 到protected/gii/model/templates/compact。若我们再次尝试以 compact 模板生成,我们会成功。但是,生成的代码和以 default 模板集生成的代码没什么不同。

现在是时候做点真正的工作了。打开文件 protected/gii/model/templates/compact/model.php 以编辑它。记得这个文件将作为类似一个视图文件被使用,意味着它可以包含 PHP 表达式和语句。让我们更改模板以便生成的代码里 attributeLabels() 方法使用 Yii::t() 来翻译属性标签:


public function attributeLabels()
{
    return array(
<?php foreach($labels as $name=>$label): ?>
            <?php echo "&#39;$name&#39; => Yii::t('application', '$label'),\n"; ?>
<?php endforeach; ?>
    );
}
登录后复制


在每个代码模板中,我们可以访问一些预定义的变量,例如上面例子中的 $labels。这些变量由对应的代码生成器提供。不同的代码生成器可能在他们的代码模板中提供不同的变量。请认真阅读默认代码模板中的描述。

创建新的生成器

In this sub-section, we show how to create a new generator that can generate a new widget class.

We first create a directory named protected/gii/widget. Under this directory, we will create the following files:

  • WidgetGenerator.php: contains the WidgetGenerator controller class. This is the entry point of the widget generator.

  • WidgetCode.php: contains the WidgetCode model class. This class has the main logic for code generation.

  • views/index.php: the view script showing the code generator input form.

  • templates/default/widget.php: the default code template for generating a widget class file.

Creating WidgetGenerator.php

The WidgetGenerator.php file is extremely simple. It only contains the following code:


class WidgetGenerator extends CCodeGenerator
{
    public $codeModel='application.gii.widget.WidgetCode';
}
登录后复制


In the above code, we specify that the generator will use the model class whose path alias isapplication.gii.widget.WidgetCode. The WidgetGenerator class extends from CCodeGenerator which implements a lot of functionalities, including the controller actions needed to coordinate the code generation process.

Creating WidgetCode.php

The WidgetCode.php file contains the WidgetCode model class that has the main logic for generating a widget class based on the user input. In this example, we assume that the only input we want from the user is the widget class name. Our WidgetCode looks like the following:



class WidgetCode extends CCodeModel
{
    public $className;

    public function rules()
    {
        return array_merge(parent::rules(), array(
            array('className', 'required'),
            array('className', 'match', 'pattern'=>'/^\w+$/'),
        ));
    }

    public function attributeLabels()
    {
        return array_merge(parent::attributeLabels(), array(
            'className'=>'Widget Class Name',
        ));
    }

    public function prepare()
    {
        $path=Yii::getPathOfAlias('application.components.' . $this->className) . '.php';
        $code=$this->render($this->templatepath.'/widget.php');

        $this->files[]=new CCodeFile($path, $code);
    }
}
登录后复制


The WidgetCode class extends from CCodeModel. Like a normal model class, in this class we can declarerules() and attributeLabels() to validate user inputs and provide attribute labels, respectively. Note that because the base class CCodeModel already defines some rules and attribute labels, we should merge them with our new rules and labels here.

The prepare() method prepares the code to be generated. Its main task is to prepare a list of CCodeFileobjects, each of which represent a code file being generated. In our example, we only need to create oneCCodeFile object that represents the widget class file being generated. The new widget class will be generated under the protected/components directory. We call CCodeFile::render method to generate the actual code. This method includes the code template as a PHP script and returns the echoed content as the generated code.

Creating views/index.php

Having the controller (WidgetGenerator) and the model (WidgetCode), it is time for us to create the viewviews/index.php.



<h1>Widget Generator</h1>

<?php $form=$this->beginWidget('CCodeForm', array('model'=>$model)); ?>

    <p class="row">
        <?php echo $form->labelEx($model,'className'); ?>
        <?php echo $form->textField($model,'className',array('size'=>65)); ?>
        <p class="tooltip">
            Widget class name must only contain word characters.
        </p>
        <?php echo $form->error($model,'className'); ?>
    </p>

<?php $this->endWidget(); ?>
登录后复制


In the above, we mainly display a form using the CCodeForm widget. In this form, we display the field to collect the input for the className attribute in WidgetCode.

When creating the form, we can exploit two nice features provided by the CCodeForm widget. One is about input tooltips. The other is about sticky inputs.

If you have tried any default code generator, you will notice that when setting focus in one input field, a nice tooltip will show up next to the field. This can easily achieved here by writing next to the input field a p whose CSS class is tooltip.

For some input fields, we may want to remember their last valid values so that the user can save the trouble of re-entering them each time they use the generator to generate code. An example is the input field collecting the controller base class name default controller generator. These sticky fields are initially displayed as highlighted static text. If we click on them, they will turn into input fields to take user inputs.

In order to declare an input field to be sticky, we need to do two things.

First, we need to declare a sticky validation rule for the corresponding model attribute. For example, the default controller generator has the following rule to declare that baseClass and actions attributes are sticky:



public function rules()
{
    return array_merge(parent::rules(), array(
        ......
        array('baseClass, actions', 'sticky'),
    ));
}
登录后复制


Second, we need to add a CSS class named sticky to the container p of the input field in the view, like the following:



<p class="row sticky">
    ...input field here...
</p>
登录后复制


Creating templates/default/widget.php

Finally, we create the code template templates/default/widget.php. As we described earlier, this is used like a view script that can contain PHP expressions and statements. In a code template, we can always access the $this variable which refers to the code model object. In our example, $this refers to the WidgetModelobject. We can thus get the user-entered widget class name via $this->className.



<?php echo &#39;<?php&#39;; ?>

class <?php echo $this->className; ?> extends CWidget
{
    public function run()
    {

    }
}
登录后复制


This concludes the creation of a new code generator. We can access this code generator immediately via the URL http://www.php.cn

 以上就是Yii框架官方指南系列41——专题:自动代码生成的内容,更多相关内容请关注PHP中文网(www.php.cn)!


本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Java教程
1659
14
CakePHP 教程
1415
52
Laravel 教程
1309
25
PHP教程
1257
29
C# 教程
1232
24
Yii框架中的RESTful API开发 Yii框架中的RESTful API开发 Jun 21, 2023 pm 12:34 PM

Yii是一款基于PHP的高性能MVC框架,它提供了非常丰富的工具和功能,支持快速、高效地开发Web应用程序。其中,Yii框架的RESTfulAPI功能得到了越来越多开发者的关注和喜爱,因为使用Yii框架可以非常方便地构建出高性能、易扩展的RESTful接口,为Web应用的开发提供了强有力的支持。RESTfulAPI简介RESTfulAPI是一种基于

Yii框架中间件:为应用程序提供多重数据存储支持 Yii框架中间件:为应用程序提供多重数据存储支持 Jul 28, 2023 pm 12:43 PM

Yii框架中间件:为应用程序提供多重数据存储支持介绍中间件(middleware)是Yii框架中的一个重要概念,它为应用程序提供了多重数据存储支持。中间件的作用类似于一个过滤器,它能够在应用程序的请求和响应之间插入自定义代码。通过中间件,我们可以对请求进行处理、验证、过滤,然后将处理后的结果传递给下一个中间件或最终的处理程序。Yii框架中的中间件使用起来非常

使用Yii框架创建游戏攻略网站 使用Yii框架创建游戏攻略网站 Jun 21, 2023 pm 01:45 PM

近年来,随着游戏行业的快速发展,越来越多的玩家开始寻找游戏攻略来帮助游戏过关。因此,创建一个游戏攻略网站可以让玩家们更加方便地获取游戏攻略,同时也能为玩家提供更好的游戏体验。在创建这样一个网站时,我们可以使用Yii框架来进行开发。Yii框架是一个基于PHP编程语言的Web应用开发框架。它具有高效、安全、扩展性强等特点,可以为我们更快速、高效地创建一个游戏攻略

使用Yii框架实现网页缓存和页面分块的步骤 使用Yii框架实现网页缓存和页面分块的步骤 Jul 30, 2023 am 09:22 AM

使用Yii框架实现网页缓存和页面分块的步骤引言:在Web开发过程中,为了提高网站的性能和用户体验,常常需要对页面进行缓存和分块处理。Yii框架提供了强大的缓存和布局功能,可以帮助开发者快速实现网页缓存和页面分块,本文将介绍如何使用Yii框架进行网页缓存和页面分块的实现。一、网页缓存开启网页缓存在Yii框架中,可以通过配置文件来开启网页缓存。打开主配置文件co

PHP中如何使用Yii框架 PHP中如何使用Yii框架 Jun 27, 2023 pm 07:00 PM

随着Web应用程序的快速发展,现代Web开发已成为一项重要技能。许多框架和工具可用于开发高效的Web应用程序,其中Yii框架就是一个非常流行的框架。Yii是一个高性能、基于组件的PHP框架,它采用了最新的设计模式和技术,提供了强大的工具和组件,是构建复杂Web应用程序的理想选择。在本文中,我们将讨论如何使用Yii框架来构建Web应用程序。安装Yii框架首先,

Yii框架中间件:为应用程序添加日志记录和调试功能 Yii框架中间件:为应用程序添加日志记录和调试功能 Jul 28, 2023 pm 08:49 PM

Yii框架中间件:为应用程序添加日志记录和调试功能【引言】在开发Web应用程序时,我们通常需要添加一些附加功能以提高应用的性能和稳定性。Yii框架提供了中间件的概念,使我们能够在应用程序处理请求之前和之后执行一些额外的任务。本文将介绍如何使用Yii框架的中间件功能来实现日志记录和调试功能。【什么是中间件】中间件是指在应用程序处理请求之前和之后,对请求和响应做

在Yii框架中使用控制器(Controllers)处理Ajax请求的方法 在Yii框架中使用控制器(Controllers)处理Ajax请求的方法 Jul 28, 2023 pm 07:37 PM

在Yii框架中,控制器(Controllers)扮演着处理请求的重要角色。除了处理常规的页面请求之外,控制器还可以用于处理Ajax请求。本文将介绍在Yii框架中处理Ajax请求的方法,并提供代码示例。在Yii框架中,处理Ajax请求可以通过以下步骤进行:第一步,创建一个控制器(Controller)类。可以通过继承Yii框架提供的基础控制器类yiiwebCo

Yii框架中的调试工具:分析和调试应用程序 Yii框架中的调试工具:分析和调试应用程序 Jun 21, 2023 pm 06:18 PM

在现代的Web应用程序开发中,调试工具是不可或缺的。它们可以帮助开发者查找和解决应用程序的各种问题。Yii框架作为一款流行的Web应用程序框架,自然也提供了一些调试工具。本文将重点介绍Yii框架中的调试工具,并讨论它们如何帮助我们分析和调试应用程序。GiiGii是Yii框架的代码生成器。它可以自动生成Yii应用程序的代码,如模型、控制器和视图等。使用Gii,

See all articles