Table of Contents
1. Using Gii
2. Extending Gii
Code Generator Architecture
Generator search path
Customized code template
创建新的生成器
Home Backend Development PHP Tutorial Yii Framework Official Guide Series 41 - Special Topic: Automatic Code Generation

Yii Framework Official Guide Series 41 - Special Topic: Automatic Code Generation

Feb 16, 2017 am 09:15 AM

Since version 1.1.2, Yii is equipped with a code generation tool based on the web interfaceGii. It replaces the previous command line code generation tool yiic shell. In this part, we will explain how to use Gii and how to extend Gii to increase our development results.

1. Using Gii

Gii is implemented as a module, and it must be used in an existing Yii application. To use Gii, we first change the configuration of the application as follows:


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


In the above, we declared a file called The module of gii, its class is GiiModule. We have also set a password for this module. When we access Gii, there will be an input box asking to fill in the password.

For security reasons, only local access to Gii is allowed by default. To allow other trusted machines to access it, we need to configure the GiiModule::ipFilters property as shown above.

Because Gii will generate and save new files to the application, we need to ensure that the web server process has permission to do so. The GiiModule::newFileMode and GiiModule::newDirMode properties above control how new files and directories are generated.

Note: Gii is mainly used as a development tool. Therefore, it should be installed only on development machines. Because it can generate new PHP files in the application, we should pay enough attention to security issues (such as setting passwords, IP filtering).

Gii can now be accessed through the URL http://www.php.cn/. Here we assume that http://www.php.cn/ is the URL to access the Yii application.

If the Yii application uses a URL in the path format (see URL management), we can access Gii through the URL http://www.php.cn/. We may need to add the following URL rules in front of the existing URL rules:

'components'=>array(
    ......
    'urlManager'=>array(
        'urlFormat'=>'path',
        'rules'=>array(
            'gii'=>'gii',
            'gii/<controller:\w+>'=>'gii/<controller>',
            'gii/<controller:\w+>/<action:\w+>'=>'gii/<controller>/<action>',
            ...已有的规则...
        ),
    ),
)
Copy after login


Gii has some default code generators. Each code generator is responsible for generating a specific type of code. For example, the controller generator generates a controller class and some action view scripts; the model generator generates an ActiveRecord class for the specified data table.

The basic process of using a generator is as follows:

  1. Enter the generator page;

  2. Fill in the specified code generation parameters Input box. For example, to use Module Generator to create a new module, you need to specify the module ID;

  3. Click the Preview button to preview the code that will be generated. You will see a table listing the files that will be generated. You can click on any of the files to preview the code;

  4. Click the Generate button to generate these code files;

  5. View Code generation log.

2. Extending Gii

Although the default Gii code generators can generate very powerful code, we often want to customize them or create a new one to suit our needs tastes and needs. For example, we want the generated code to be in the style we like, or we want the code to support multiple languages. All of this is very easy to implement in Gii.

Gii can be extended in 2 ways: customizing code templates for existing code generators, and writing new code generators.

Code Generator Architecture

A code generator is stored in a directory, and the name of this directory is considered the name of the generator. The directory usually consists of the following:

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
Copy after login

Generator search path

Gii searches for available generators in the directory specified by the GiiModule::generatorPaths property. When customization is required, we can make the following configuration in the application's configuration file,


return array(
    'modules'=>array(
        'gii'=>array(
            'class'=>'system.gii.GiiModule',
            'generatorPaths'=>array(
                'application.gii',   // a path alias
            ),
        ),
    ),
);
Copy after login


The above configuration tells Gii to use the alias Generators are found in the directory of application.gii, and the default location is system.gii.generators.

It is also possible to have generators with the same name in different search paths. In this case, the generator that appears first in the directory specified by GiiModule::generatorPaths has priority.

Customized code template

This is the easiest and most common way to extend Gii. We use an example to introduce how to customize the code template. Suppose we want to customize the code generated by the model generator.

We first create a directory named protected/gii/model/templates/compact. The model here means we are going to override the default model generator. templates/compact means we will add a new code template set named compact.

Then we add application.gii to GiiModule::generatorPaths in the application configuration. As shown above.

现在打开 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; ?>
    );
}
Copy after login


在每个代码模板中,我们可以访问一些预定义的变量,例如上面例子中的 $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';
}
Copy after login


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);
    }
}
Copy after login


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(); ?>
Copy after login


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'),
    ));
}
Copy after login


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>
Copy after login


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()
    {

    }
}
Copy after login


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)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

RESTful API development in Yii framework RESTful API development in Yii framework Jun 21, 2023 pm 12:34 PM

Yii is a high-performance MVC framework based on PHP. It provides a very rich set of tools and functions to support the rapid and efficient development of web applications. Among them, the RESTful API function of the Yii framework has attracted more and more attention and love from developers, because using the Yii framework can easily build high-performance and easily scalable RESTful interfaces, providing strong support for the development of web applications. . Introduction to RESTfulAPI RESTfulAPI is a

How to use Yii framework in PHP How to use Yii framework in PHP Jun 27, 2023 pm 07:00 PM

With the rapid development of web applications, modern web development has become an important skill. Many frameworks and tools are available for developing efficient web applications, among which the Yii framework is a very popular framework. Yii is a high-performance, component-based PHP framework that uses the latest design patterns and technologies, provides powerful tools and components, and is ideal for building complex web applications. In this article, we will discuss how to use Yii framework to build web applications. Install Yii framework first,

Steps to implement web page caching and page chunking using Yii framework Steps to implement web page caching and page chunking using Yii framework Jul 30, 2023 am 09:22 AM

Steps to implement web page caching and page chunking using the Yii framework Introduction: During the web development process, in order to improve the performance and user experience of the website, it is often necessary to cache and chunk the page. The Yii framework provides powerful caching and layout functions, which can help developers quickly implement web page caching and page chunking. This article will introduce how to use the Yii framework to implement web page caching and page chunking. 1. Turn on web page caching. In the Yii framework, web page caching can be turned on through the configuration file. Open the main configuration file co

Yii framework middleware: providing multiple data storage support for applications Yii framework middleware: providing multiple data storage support for applications Jul 28, 2023 pm 12:43 PM

Yii framework middleware: providing multiple data storage support for applications Introduction Middleware (middleware) is an important concept in the Yii framework, which provides multiple data storage support for applications. Middleware acts like a filter, inserting custom code between an application's requests and responses. Through middleware, we can process, verify, filter requests, and then pass the processed results to the next middleware or final handler. Middleware in the Yii framework is very easy to use

Create a game guide website using Yii framework Create a game guide website using Yii framework Jun 21, 2023 pm 01:45 PM

In recent years, with the rapid development of the game industry, more and more players have begun to look for game strategies to help them pass the game. Therefore, creating a game guide website can make it easier for players to obtain game guides, and at the same time, it can also provide players with a better gaming experience. When creating such a website, we can use the Yii framework for development. The Yii framework is a web application development framework based on the PHP programming language. It has the characteristics of high efficiency, security, and strong scalability, and can help us create a game guide more quickly and efficiently.

Yii Framework Middleware: Add logging and debugging capabilities to your application Yii Framework Middleware: Add logging and debugging capabilities to your application Jul 28, 2023 pm 08:49 PM

Yii framework middleware: Add logging and debugging capabilities to applications [Introduction] When developing web applications, we usually need to add some additional features to improve the performance and stability of the application. The Yii framework provides the concept of middleware that enables us to perform some additional tasks before and after the application handles the request. This article will introduce how to use the middleware function of the Yii framework to implement logging and debugging functions. [What is middleware] Middleware refers to the processing of requests and responses before and after the application processes the request.

How to use controllers to handle Ajax requests in the Yii framework How to use controllers to handle Ajax requests in the Yii framework Jul 28, 2023 pm 07:37 PM

In the Yii framework, controllers play an important role in processing requests. In addition to handling regular page requests, controllers can also be used to handle Ajax requests. This article will introduce how to handle Ajax requests in the Yii framework and provide code examples. In the Yii framework, processing Ajax requests can be carried out through the following steps: The first step is to create a controller (Controller) class. You can inherit the basic controller class yiiwebCo provided by the Yii framework

Encrypt and decrypt sensitive data using Yii framework middleware Encrypt and decrypt sensitive data using Yii framework middleware Jul 28, 2023 pm 07:12 PM

Encrypting and decrypting sensitive data using Yii framework middleware Introduction: In modern Internet applications, privacy and data security are very important issues. To ensure that users' sensitive data is not accessible to unauthorized visitors, we need to encrypt this data. The Yii framework provides us with a simple and effective way to implement the functions of encrypting and decrypting sensitive data. In this article, we’ll cover how to achieve this using the Yii framework’s middleware. Introduction to Yii framework Yii framework is a high-performance PHP framework.

See all articles