Browse Source

translate to russian language

tags/2.0.0-rc
LAV45 10 years ago
parent
commit
42210b5f2c
  1. 107
      docs/guide-ru/start-gii.md

107
docs/guide-ru/start-gii.md

@ -1,22 +1,22 @@
Generating Code with Gii
Генерация кода при помощи Gii
========================
This section will describe how to use [Gii](tool-gii.md) 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 to the instructions shown on the Gii Web pages.
В этом разделе, мы опишем как использовать [Gii](tool-gii.md) для автоматической генерации кода
реализующий некоторые общие особенности. Для достижения этой цели, все что вам нужно это просто ввести необходимую информацию в соответствии с инструкциями отображаемыми на веб-страницах Gii.
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
* Как включить Gii в приложении;
* Как использовать Gii для создания Active Record класса;
* Как использовать Gii для генерироции кода реализующего CRUD для таблицы БД.
* Как настроить код генерируемый Gii.
Starting Gii <a name="starting-gii"></a>
Запускаем Gii <a name="starting-gii"></a>
------------
[Gii](tool-gii.md) is provided in Yii as a [module](structure-modules.md). 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:
[Gii](tool-gii.md) поставляется в Yii как [модуль](structure-modules.md). Вы можете включить Gii
настроив его свойство [[yii\base\Application::modules|modules]] приложения. В частности, вы можете найти следующий код уже приведен в `config/web.php` файле - настройки приложения,
```php
$config = [ ... ];
@ -27,17 +27,17 @@ if (YII_ENV_DEV) {
}
```
The above configuration states that when in [development environment](concept-configurations.md#environment-constants),
the application should include a module named `gii`, which is of class [[yii\gii\Module]].
Приведенная выше конфигурация показывает, что когда в [среде разработки](concept-configurations.md#environment-constants),
приложение должно включать в себя модуль с именем `gii`, который реализует класс [[yii\gii\Module]].
If you check the [entry script](structure-entry-scripts.md) `web/index.php` of your application, you will
find the following line, which essentially makes `YII_ENV_DEV` to be true.
Если вы проверите [входной скрипт](structure-entry-scripts.md) `web/index.php` вашего приложения, вы
найдете следующую строку, которая по сути делает `YII_ENV_DEV`, чтобы быть правдой.
```php
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:
Благодаря этой строке, ваше приложение находится в режиме разработки, и Gii будет уже включен, в соответствии с описанной выше конфигурации. Теперь вы можете получить доступ к Gii по следующему адресу:
```
http://hostname/index.php?r=gii
@ -46,82 +46,73 @@ http://hostname/index.php?r=gii
![Gii](images/start-gii.png)
Generating an Active Record Class <a name="generating-ar"></a>
Генерация класса Active Record <a name="generating-ar"></a>
---------------------------------
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:
Для использования Gii генератора класса Active Record, выберите "Генератор модели" (нажав на ссылку на главной странице Gii). И заполните форму следующим образом:
* Table Name: `country`
* Model Class: `Country`
* Имя таблицы: `country`
* Класс модели : `Country`
![Model Generator](images/start-gii-model.png)
![Генератор модели](images/start-gii-model.png)
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.
Затем нажмите на кнопку "Предварительный просмотр". Вы увидите `models/Country.php` перечислен в результатах файл класса, который будет создан. Вы можете нажать на имя файла класса, для просмотра его содержимого.
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.
При использовании Gii, если вы уже создали такой же файл и хотите перезаписать его, нажмите кнопку `различия` рядом с именем файла, чтобы увидеть различия между генерируемого кода и существующей версии.
![Model Generator Preview](images/start-gii-model-preview.png)
![Предварительный просмотр генератора модели](images/start-gii-model-preview.png)
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 <a name="generating-crud"></a>
Создание CRUD кода <a name="generating-crud"></a>
--------------------
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:
CRUD расшифровывается как Создать, Читать, Обновить, и Удалить, представляющих четыре общие задачи, принятые с данными на большинстве веб-сайтов. Чтобы создать функциональность CRUD используйте Gii, выберите "CRUD Генератор" (нажав на ссылку на главной странице GII). Для «country», например, заполнить полученную форму следующим образом:
* Model Class: `app\models\Country`
* Search Model Class: `app\models\CountrySearch`
* Controller Class: `app\controllers\CountryController`
* Класс модели : `app\models\Country`
* Класс модели поиска: `app\models\CountrySearch`
* Класс контроллера: `app\controllers\CountryController`
![CRUD Generator](images/start-gii-crud.png)
![CRUD генератор](images/start-gii-crud.png)
Next, click on the "Preview" button. You will see a list of files to be generated, as shown below.
Затем, нажмите на кнопку "Предварительный просмотр". Вы увидите список файлов, которые будут созданы, как показано ниже.
[[NEED THE IMAGE HERE]]
[[ЗДЕСЬ НУЖНА КАРТИНКА]]
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.)
Если вы ранее создали `controllers/CountryController.php` и `views/country/index.php` файлы (в разделе базы данных направляющей), установите флажок "переписать", чтобы заменить их. (Предыдущие версии не имеют полной поддержку CRUD.)
Trying it Out <a name="trying-it-out"></a>
Пытается его <a name="trying-it-out"></a>
-------------
To see how it works, use your browser to access the following URL:
Чтобы увидеть как она работает, используйте ваш браузер для доступа к следующему URL:
```
http://hostname/index.php?r=country/index
```
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](images/start-gii-country-grid.png)
![Таблица данных стран](images/start-gii-country-grid.png)
![Updating a Country](images/start-gii-country-update.png)
![Обновление страны](images/start-gii-country-update.png)
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:
Ниже приведен список файлов созданных с помощью Gii, в случае если вы хотите исследовать эту реализацию функций, или их настройки:
* Controller: `controllers/CountryController.php`
* Models: `models/Country.php` and `models/CountrySearch.php`
* Views: `views/country/*.php`
* Контроллер: `controllers/CountryController.php`
* Модели: `models/Country.php` and `models/CountrySearch.php`
* Вид: `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](tool-gii.md) section.
> Информация: Gii разработан как высоко настраиваемый и расширяемый инструмент генерации кода. Используя его с умом может значительно ускорить скорость разработки приложений. Для более подробной информации, пожалуйста обратитесь к разделу [Gii](tool-gii.md).
Summary <a name="summary"></a>
Заключение <a name="summary"></a>
-------
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.
В этом разделе, Вы узнали как использовать Gii чтобы генерировать код который реализует полный функциональность CRUD для содержимого которое хранится в таблице базы данных.
Loading…
Cancel
Save