tool-gii.md 8.49 KB
Newer Older
1 2 3
The Gii code generation tool
============================

4
> Note: This section is under development.
Qiang Xue committed
5

6
Yii includes a handy tool, named Gii, that provides rapid prototyping by generating commonly used code snippets
7 8
as well as complete CRUD controllers.

Carsten Brandt committed
9

10 11 12
Installing and configuring
--------------------------

13
Gii is an official Yii extension. The preferred way to install this extension is through
14
[composer](http://getcomposer.org/download/).
Carsten Brandt committed
15

16
You can either run this command:
Carsten Brandt committed
17 18

```
19
php composer.phar require --prefer-dist yiisoft/yii2-gii "*"
Carsten Brandt committed
20 21
```

22
Or you can add this code to the require section of your `composer.json` file:
Carsten Brandt committed
23 24 25 26 27

```
"yiisoft/yii2-gii": "*"
```

28
Once the Gii extension has been installed, you enable it by adding these lines to your application configuration file:
29 30

```php
31 32 33 34 35
return [
    'bootstrap' => ['gii'],
    'modules' => [
        'gii' => 'yii\gii\Module',
        // ...
36
    ],
37 38
    // ...
];
39 40
```

Carsten Brandt committed
41 42 43 44 45 46
You can then access Gii through the following URL:

```
http://localhost/path/to/index.php?r=gii
```

47 48 49 50 51 52 53 54 55
If you have enabled pretty URLs, you may use the following URL:

```
http://localhost/path/to/index.php/gii
```


> Note: if you are accessing gii from an IP address other than localhost, access will be denied by default.
> To circumvent that default, add the allowed IP addresses to the configuration:
Alexander Makarov committed
56
>
57 58
```php
'gii' => [
59 60
    'class' => 'yii\gii\Module',
    'allowedIPs' => ['127.0.0.1', '::1', '192.168.0.*', '192.168.178.20'] // adjust this to your needs
61 62 63 64 65 66 67 68 69 70
],
```

### Basic application

In basic application template configuration structure is a bit different so Gii should be configured in
`config/web.php`:

```php
// ...
71
if (YII_ENV_DEV) {
72
    // configuration adjustments for 'dev' environment
73
    $config['bootstrap'][] = 'debug';
74
    $config['modules']['debug'] = 'yii\debug\Module';
75 76

    $config['bootstrap'][] = 'gii';
77
    $config['modules']['gii'] = 'yii\gii\Module'; // <--- here
78 79 80 81 82 83
}
```

So in order to adjust IP address you need to do it like the following:

```php
84
if (YII_ENV_DEV) {
85
    // configuration adjustments for 'dev' environment
86
    $config['bootstrap'][] = 'debug';
87
    $config['modules']['debug'] = 'yii\debug\Module';
88 89

    $config['bootstrap'][] = 'gii';
90 91 92 93
    $config['modules']['gii'] = [
        'class' => 'yii\gii\Module',
        'allowedIPs' => ['127.0.0.1', '::1', '192.168.0.*', '192.168.178.20'],
    ];
94 95
}
```
Carsten Brandt committed
96

97 98 99
How to use it
-------------

Carsten Brandt committed
100 101 102 103 104 105
When you open Gii you first see the entry page that lets you choose a generator.

![Gii entry page](images/gii-entry.png)

By default there are the following generators available:

Carsten Brandt committed
106 107
- **Model Generator** - This generator generates an ActiveRecord class for the specified database table.
- **CRUD Generator** - This generator generates a controller and views that implement CRUD (Create, Read, Update, Delete)
Carsten Brandt committed
108
  operations for the specified data model.
Carsten Brandt committed
109
- **Controller Generator** - This generator helps you to quickly generate a new controller class, one or several
Carsten Brandt committed
110
  controller actions and their corresponding views.
Carsten Brandt committed
111
- **Form Generator** - This generator generates a view script file that displays a form to collect input for the
Carsten Brandt committed
112
  specified model class.
Carsten Brandt committed
113
- **Module Generator** - This generator helps you to generate the skeleton code needed by a Yii module.
Evgeniy Tkachenko committed
114
- **Extension Generator** - This generator helps you to generate the files needed by a Yii extension.
Carsten Brandt committed
115 116 117

After choosing a generator by clicking on the "Start" button you will see a form that allows you to configure the
parameters of the generator. Fill out the form according to your needs and press the "Preview" button to get a
118 119
preview of the code that gii is about to generated. Depending on the generator you chose and whether the files
already existed or not, you will get an output similar to what you see in the following picture:
Carsten Brandt committed
120 121 122 123 124 125 126

![Gii preview](images/gii-preview.png)

Clicking on the file name you can view a preview of the code that will be generated for that file.
When the file already exists, gii also provides a diff view that shows what is different between the code that exists
and the one that will be generated. In this case you can also choose which files should be overridden and which not.

Carsten Brandt committed
127 128 129 130 131
> Tip: When using the Model Generator to update models after database change, you can copy the code from gii preview
  and merge the changes with your own code. You can use IDE features like PHPStorms
  [compare with clipboard](http://www.jetbrains.com/phpstorm/webhelp/comparing-files.html) for this,
  which allows you to merge in relevant changes and leave out others that may revert your own code.

Carsten Brandt committed
132 133 134
After you have reviewed the code and selected the files to be generated you can click the "Generate" button to create
the files. If all went fine you are done. When you see errors that gii is not able to generate the files you have to
adjust directory permissions so that your webserver is able to write to the directories and create the files.
135 136 137 138

> Note: The code generated by gii is only a template that has to be adjusted to your needs. It is there
  to help you create new things quickly but it is not something that creates ready to use code.
  We often see people using the models generated by gii without change and just extend them to adjust
139
  some parts of it. This is not how it is meant to be used. Code generated by gii may be incomplete or incorrect
140 141
  and has to be changed to fit your needs before you can use it.

Carsten Brandt committed
142

143 144 145
Creating your own templates
---------------------------

Evgeniy Tkachenko committed
146 147
Every generator has a form field `Code Template` that lets you choose a template to use for code generation.
By default gii only provides one template `default` but you can create your own templates that are adjusted to your needs.
Carsten Brandt committed
148

Evgeniy Tkachenko committed
149 150 151 152 153 154 155 156 157 158 159
If you open a folder `@app\vendor\yiisoft\yii2-gii\generators`, you'll see six folders of generators.
```
+ controller
- crud
    + default
+ extension
+ form
+ model
+ module
```
This is name generator. If you open any of these folders, you can see the folder `default`. This folder is name of the template.
Carsten Brandt committed
160

161 162 163
Copy folder `@app\vendor\yiisoft\yii2-gii\generators\crud\default` to another location, for example `@app\myTemplates\crud\`.
Now open this folder and modify any template to fit your desires, for example, add `errorSummary` in `views\_form.php`:

Evgeniy Tkachenko committed
164 165 166 167 168 169 170 171 172 173 174 175
```php
<?php
//...
<div class="<?= Inflector::camel2id(StringHelper::basename($generator->modelClass)) ?>-form">

    <?= "<?php " ?>$form = ActiveForm::begin(); ?>
    <?= "<?=" ?> $form->errorSummary($model) ?> <!-- ADDED HERE -->
    <?php foreach ($safeAttributes as $attribute) {
        echo "    <?= " . $generator->generateActiveField($attribute) . " ?>\n\n";
    } ?>
//...
```
176 177 178

Now you need to tell GII about our template.The setting is made in the config file:

Evgeniy Tkachenko committed
179
```php
180 181
// config/web.php for basic app
// ...
Evgeniy Tkachenko committed
182 183 184 185
if (YII_ENV_DEV) {    
    $config['modules']['gii'] = [
        'class' => 'yii\gii\Module',      
        'allowedIPs' => ['127.0.0.1', '::1', '192.168.0.*', '192.168.178.20'],  
186 187 188 189 190
        'generators' => [ //here
            'crud' => [ //name generator
                'class' => 'yii\gii\generators\crud\Generator', //class generator
                'templates' => [ //setting for out templates
                    'myCrud' => '@app\myTemplates\crud\default', //name template => path to template
Evgeniy Tkachenko committed
191 192 193 194 195 196 197
                ]
            ]
        ],
    ];
}
```
Open the CRUD generator and you will see that in the field `Code Template` of form appeared own template .
Carsten Brandt committed
198

Carsten Brandt committed
199 200 201
Creating your own generators
----------------------------

202 203 204 205
Open the folder of any generator and you will see two files `form.php` and `Generator.php`.
One is the form, the second is the class generator. For create your own generator, you need to create or
override these classes in any folder. Again as in the previous paragraph customize configuration:

Evgeniy Tkachenko committed
206 207 208 209 210 211 212
```php
//config/web.php for basic app
//..
if (YII_ENV_DEV) {    
    $config['modules']['gii'] = [
        'class' => 'yii\gii\Module',      
        'allowedIPs' => ['127.0.0.1', '::1', '192.168.0.*', '192.168.178.20'],  
213 214 215 216 217
         'generators' => [
            'myCrud' => [
                'class' => 'app\myTemplates\crud\Generator',
                'templates' => [
                    'my' => '@app/myTemplates/crud/default',
Evgeniy Tkachenko committed
218 219 220 221 222 223 224 225 226 227 228
                ]
            ]
        ],
    ];
}
```

```php
// @app/myTemplates/crud/Generator.php
<?php
namespace app\myTemplates\crud;
229

Evgeniy Tkachenko committed
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
class Generator extends \yii\gii\Generator
{
    public function getName()
    {
        return 'MY CRUD Generator';
    }

    public function getDescription()
    {
        return 'My crud generator. The same as a native, but he is mine...';
    }
    
    // ...
}
```
245 246

Open Gii Module and you will see a new generator appears in it.
247