tool-gii.md 9.39 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.

Qiang Xue committed
9 10 11
Gii provides a Web-based interface for you to interactively generate the code you want. It also provides a
command line interface for people who prefer to work with their console windows most of the time.

Carsten Brandt committed
12

13 14 15
Installing and configuring
--------------------------

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

19
You can either run this command:
Carsten Brandt committed
20 21

```
22
composer require "yiisoft/yii2-gii:*"
Carsten Brandt committed
23 24
```

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

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

31
Once the Gii extension has been installed, you enable it by adding these lines to your application configuration file:
32 33

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

Carsten Brandt committed
44 45 46 47 48 49
You can then access Gii through the following URL:

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

50 51 52 53 54 55 56 57
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
58
>
59 60
```php
'gii' => [
61 62
    'class' => 'yii\gii\Module',
    'allowedIPs' => ['127.0.0.1', '::1', '192.168.0.*', '192.168.178.20'] // adjust this to your needs
63 64 65
],
```

Qiang Xue committed
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
If you have configured Gii similarly in your console application configuration, you may also access Gii through
command window like the following:

```
# change path to your application's base path
cd path/to/AppBasePath

# show help information about Gii
yii help gii

# show help information about the model generator in Gii
yii help gii/model

# generate City model from city table
yii gii/model --tableName=city --modelClass=City
```


84 85 86 87 88 89 90
### Basic application

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

```php
// ...
91
if (YII_ENV_DEV) {
92
    // configuration adjustments for 'dev' environment
93
    $config['bootstrap'][] = 'debug';
94
    $config['modules']['debug'] = 'yii\debug\Module';
95 96

    $config['bootstrap'][] = 'gii';
97
    $config['modules']['gii'] = 'yii\gii\Module'; // <--- here
98 99 100 101 102 103
}
```

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

```php
104
if (YII_ENV_DEV) {
105
    // configuration adjustments for 'dev' environment
106
    $config['bootstrap'][] = 'debug';
107
    $config['modules']['debug'] = 'yii\debug\Module';
108 109

    $config['bootstrap'][] = 'gii';
110 111 112 113
    $config['modules']['gii'] = [
        'class' => 'yii\gii\Module',
        'allowedIPs' => ['127.0.0.1', '::1', '192.168.0.*', '192.168.178.20'],
    ];
114 115
}
```
Carsten Brandt committed
116

117 118 119
How to use it
-------------

Carsten Brandt committed
120 121 122 123 124 125
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
126 127
- **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
128
  operations for the specified data model.
Carsten Brandt committed
129
- **Controller Generator** - This generator helps you to quickly generate a new controller class, one or several
Carsten Brandt committed
130
  controller actions and their corresponding views.
Carsten Brandt committed
131
- **Form Generator** - This generator generates a view script file that displays a form to collect input for the
Carsten Brandt committed
132
  specified model class.
Carsten Brandt committed
133
- **Module Generator** - This generator helps you to generate the skeleton code needed by a Yii module.
Evgeniy Tkachenko committed
134
- **Extension Generator** - This generator helps you to generate the files needed by a Yii extension.
Carsten Brandt committed
135 136 137

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
138
preview of the code that Gii is about to generate. Depending on the generator you chose and whether the files
139
already existed or not, you will get an output similar to what you see in the following picture:
Carsten Brandt committed
140 141 142 143

![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.
144
When the file already exists, Gii also provides a diff view that shows what is different between the code that exists
Carsten Brandt committed
145 146
and the one that will be generated. In this case you can also choose which files should be overridden and which not.

147
> Tip: When using the Model Generator to update models after database change, you can copy the code from Gii preview
Carsten Brandt committed
148
  and merge the changes with your own code. You can use IDE features like PHPStorms
149 150
  [compare with clipboard](http://www.jetbrains.com/phpstorm/webhelp/comparing-files.html), [Aptana Studio](http://www.aptana.com/products/studio3/download) or [Eclipse](http://www.eclipse.org/pdt/) based editor also allows [compare with clipboard](http://andrei.gmxhome.de/anyedit/examples.html) by using [AnyEdit tools plugin](http://andrei.gmxhome.de/anyedit/) for this, which allows you to merge in relevant changes and leave out others that may revert your own code.
  
Carsten Brandt committed
151

Carsten Brandt committed
152
After you have reviewed the code and selected the files to be generated you can click the "Generate" button to create
153
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
Carsten Brandt committed
154
adjust directory permissions so that your webserver is able to write to the directories and create the files.
155

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

Carsten Brandt committed
162

163 164 165
Creating your own templates
---------------------------

Evgeniy Tkachenko committed
166
Every generator has a form field `Code Template` that lets you choose a template to use for code generation.
167 168 169
By default Gii only provides one template `default` but you can create your own templates that are adjusted to your needs.

If you open the folder `@app\vendor\yiisoft\yii2-gii\generators`, you'll see six folders of generators.
Carsten Brandt committed
170

Evgeniy Tkachenko committed
171 172 173 174 175 176 177 178 179
```
+ controller
- crud
    + default
+ extension
+ form
+ model
+ module
```
Carsten Brandt committed
180

181 182 183
These names are the generator names. If you open any of these folders, you can see the folder `default`, which is the name of the template.

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

Evgeniy Tkachenko committed
186 187 188 189 190 191 192 193 194 195 196 197
```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";
    } ?>
//...
```
198

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

Evgeniy Tkachenko committed
201
```php
202 203
// config/web.php for basic app
// ...
Evgeniy Tkachenko committed
204 205 206 207
if (YII_ENV_DEV) {    
    $config['modules']['gii'] = [
        'class' => 'yii\gii\Module',      
        'allowedIPs' => ['127.0.0.1', '::1', '192.168.0.*', '192.168.178.20'],  
208
        'generators' => [ //here
artyhedgehog committed
209 210
            'crud' => [ // generator name
                'class' => 'yii\gii\generators\crud\Generator', // generator class
211
                'templates' => [ //setting for out templates
artyhedgehog committed
212
                    'myCrud' => '@app/myTemplates/crud/default', // template name => path to template
Evgeniy Tkachenko committed
213 214 215 216 217 218 219
                ]
            ]
        ],
    ];
}
```
Open the CRUD generator and you will see that in the field `Code Template` of form appeared own template .
Carsten Brandt committed
220

Carsten Brandt committed
221 222 223
Creating your own generators
----------------------------

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

Evgeniy Tkachenko committed
228 229 230 231 232 233 234
```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'],  
235 236 237 238 239
         'generators' => [
            'myCrud' => [
                'class' => 'app\myTemplates\crud\Generator',
                'templates' => [
                    'my' => '@app/myTemplates/crud/default',
Evgeniy Tkachenko committed
240 241 242 243 244 245 246 247 248 249 250
                ]
            ]
        ],
    ];
}
```

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

Evgeniy Tkachenko committed
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
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...';
    }
    
    // ...
}
```
267 268

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