Yii 2. Generating Code with Gii
Yii 2. Generating Code with Gii

Generating Yii 2 application code using Gii

Старт! Честный VDS/VPS, на котором «Лунная База» живет уже 20+ лет

Задумываетесь о том, чтобы поднять свой pet-проект, сайт клиента или настроить окружение для разработки? Уже пора подумать, где арендовать железо.

Лунная База хостится на FirstVDS более 20 лет. Мыслей о том, чтобы перебраться на другой хостинг, не было ни разу (хотя опыт работы с другими вариантами, конечно, есть).

Бывали разные ситуации, но они бывают на любом железе. Главное, что нужно понять: здесь нет маркетинговой шелухи и сказок про «мы всё сделаем за вас». Если вы берете VDS — вам дают полный root, возможность накатить любую ОС и не лезут в ваши конфиги.

Если в саппорт написать с вопросом по вашему коду и получить ответ: «Читайте документацию и разбирайтесь сами» или «Обратитесь к профильному специалисту» — это не повод обижаться. Это повод углубить свои знания в DevOps и сайтостроении! Бегите от тех, кто пообещает: «Мы всё чиним и настраиваем абсолютно бесплатно!». Никто никогда не работает «по доброте душевной» в ущерб себе, а бесплатный сыр в администрировании обычно заканчивается сломанной базой данных.

Что по факту: Гибкое масштабирование ядер и RAM, экономия по сравнению с физическими серверами и адекватная панель ispmanager, если она вам нужна.



Using Gii for automatic code generation in Yii 2

This section will describe how to use Gii to automatically generate code that implements some common Web site features. Using Gii to auto-generate code is simply a matter of entering the right information per the instructions shown on the Gii Web pages.

Through this tutorial, you will learn how to:

  • enable Gii in your application,
  • use Gii to generate an Active Record class,
  • use Gii to generate the code implementing the CRUD operations for a DB table,
  • customize the code generated by Gii.

Starting Gii

Gii is provided in Yii as a module. You can enable Gii by configuring it in the [[yii\base\Application::modules|modules]] property of the application. Depending upon how you created your application, you may find the following code is already provided in the config/web.php configuration file:

$config = [ ... ];

if (YII_ENV_DEV) {
    $config['bootstrap'][] = 'gii';
    $config['modules']['gii'] = [
        'class' => 'yii\gii\Module',
    ];
}

The above configuration states that when in development environment, the application should include a module named gii, which is of class [[yii\gii\Module]].

If you check the entry script web/index.php of your application, you will find the following line, which essentially makes YII_ENV_DEV to be true.

defined('YII_ENV') or define('YII_ENV', 'dev');

Thanks to that line, your application is in development mode, and will have already enabled Gii, per the above configuration. You can now access Gii via the following URL:

http://hostname/index.php?r=gii

Note: If you are accessing Gii from a machine other than localhost, the access will be denied by default for security purpose. You can configure Gii to add the allowed IP addresses as follows,

'gii' => [
    'class' => 'yii\gii\Module',
    'allowedIPs' => ['127.0.0.1', '::1', '192.168.0.*', '192.168.178.20'] // adjust this to your needs
],

Starting Gii yii 2

Generating an Active Record Class

To use Gii to generate an Active Record class, select the "Model Generator" (by clicking the link on the Gii index page). Then fill out the form as follows:

  • Table Name: country
  • Model Class: Country

Model Generator yii 2

Next, click on the "Preview" button. You will see models/Country.php is listed in the resulting class file to be created. You may click on the name of the class file to preview its content.

When using Gii, if you have already created the same file and would be overwriting it, click the diff button next to the file name to see the differences between the code to be generated and the existing version.

Model Generator Preview yii 2

When overwriting an existing file, check the box next to "overwrite" and then click the "Generate" button. If creating a new file, you can just click "Generate".

Next, you will see a confirmation page indicating the code has been successfully generated. If you had an existing file, you'll also see a message indicating that it was overwritten with the newly generated code.

Generating CRUD Code

CRUD stands for Create, Read, Update, and Delete, representing the four common tasks taken with data on most Web sites. To create CRUD functionality using Gii, select the "CRUD Generator" (by clicking the link on the Gii index page). For the "country" example, fill out the resulting form as follows:

  • Model Class: app\models\Country
  • Search Model Class: app\models\CountrySearch
  • Controller Class: app\controllers\CountryController

CRUD Generator yii 2

Next, click on the "Preview" button. You will see a list of files to be generated, as shown below.

CRUD Generator Preview yii 2

If you previously created the controllers/CountryController.php and views/country/index.php files (in the databases section of the guide), check the "overwrite" box to replace them. (The previous versions did not have full CRUD support.)

Trying it Out

To see how it works, use your browser to access the following URL:

http://hostname/index.php?r=country%2Findex

You will see a data grid showing the countries from the database table. You may sort the grid, or filter it by entering filter conditions in the column headers.

For each country displayed in the grid, you may choose to view its details, update it, or delete it. You may also click on the "Create Country" button on top of the grid to be provided with a form for creating a new country.

Data Grid of Countries gii yii 2

Updating a Country gii yii 2

The following is the list of the files generated by Gii, in case you want to investigate how these features are implemented, or to customize them:

  • Controller: controllers/CountryController.php
  • Models: models/Country.php and models/CountrySearch.php
  • Views: views/country/*.php

Info: Gii is designed to be a highly customizable and extensible code generation tool. Using it wisely can greatly accelerate your application development speed. For more details, please refer to the Gii section.

Summary

In this section, you have learned how to use Gii to generate the code that implements complete CRUD functionality for content stored in a database table.

Самый честный хостинг за 20+ лет существования Лунной Базы

Задумываешься о том, чтобы поднять свой сайт в Интернете? Уже пора подумать о том, какой хостинг выбрать?

Лунная База хостится 20+ лет на firstDVS. При этом, мыслей о том, чтобы перебраться на другой хостинг не было. (Но, при этом есть опыт работы с другими вариантами.)

Бывали с firstDVS разные ситуации, но, они бывают на всех хостингах. Единственное, что тут важно понять, - это то, что никто ничего тебе не будет впаривать... Но, и работать за тебя тоже никто не станет. Если в саппорт ответили: «Читайте по ссылке и разбирайтесь сами...» или вообще «Обратитесь за помощью к специалисту», - это повод углубить свои знания в области сайтостроения, а не бежать к тем, что пообещают: «Мы всё чиним и всё делаем за своих клиентов абсолютно бесплатно!» Никто никогда ничего ни за кого "по доброте душевной" не делал, не делает и не будет делать!

Старт! MoonВase — A Hot Start on the Internet
Старт! MoonВase — A Hot Start on the Internet
Старт! Menu