SilverFire - Dmitry Naumenko
7 years ago
632 changed files with 20018 additions and 3930 deletions
@ -0,0 +1,192 @@
|
||||
Rozszerzanie ActiveForm po stronie klienta |
||||
========================================== |
||||
|
||||
Widżet [[yii\widgets\ActiveForm]] posiada szereg wbudowanych metod JavaScript, służących do walidacji po stronie klienta. |
||||
Ich implementacja jest bardzo elastyczna i pozwala na rozszerzanie ich na wiele sposobów. |
||||
|
||||
## Zdarzenia ActiveForm |
||||
|
||||
ActiveForm wyzwala serie dedykowanych zdarzeń. Używając poniższego kodu, można przechwycić te zdarzenia i je obsłużyć: |
||||
|
||||
```javascript |
||||
$('#contact-form').on('beforeSubmit', function (e) { |
||||
if (!confirm("Wszystko jest w porządku. Wysłać formularz?")) { |
||||
return false; |
||||
} |
||||
return true; |
||||
}); |
||||
``` |
||||
|
||||
Poniżej znajdziesz opis dostępnych zdarzeń. |
||||
|
||||
### `beforeValidate` |
||||
|
||||
`beforeValidate` jest wyzwalane przed walidacją całego formularza. |
||||
|
||||
Sygnatura metody obsługującej to zdarzenie powinna wyglądać następująco: |
||||
|
||||
```javascript |
||||
function (event, messages, deferreds) |
||||
``` |
||||
|
||||
gdzie |
||||
|
||||
- `event`: obiekt Event. |
||||
- `messages`: asocjacyjna tablica, gdzie kluczami są ID atrybutów, a wartościami tablice opisów błędów dla tych atrybutów. |
||||
- `deferreds`: tablica obiektów kolejkujących. Możesz użyć `deferreds.add(callback)`, aby dodać nową walidację do kolejki. |
||||
|
||||
Jeśli metoda obsługująca zwróci boolean `false`, zatrzyma dalszą walidację formularza. W takim wypadku zdarzenie |
||||
`afterValidate` nie będzie już wyzwalane. |
||||
|
||||
### `afterValidate` |
||||
|
||||
`afterValidate` jest wyzwalane po walidacji całego formularza. |
||||
|
||||
Sygnatura metody obsługującej to zdarzenie powinna wyglądać następująco: |
||||
|
||||
```javascript |
||||
function (event, messages, errorAttributes) |
||||
``` |
||||
|
||||
gdzie |
||||
|
||||
- `event`: obiekt Event. |
||||
- `messages`: asocjacyjna tablica, gdzie kluczami są ID atrybutów, a wartościami tablice opisów błędów dla tych atrybutów. |
||||
- `errorAttributes`: tablica atrybutów z błędami walidacji. Sprawdź konstrukcję `attributeDefaults`, aby dowiedzieć się więcej o strukturze tego parametru. |
||||
|
||||
### `beforeValidateAttribute` |
||||
|
||||
`beforeValidateAttribute` jest wyzwalane przed walidacją atrybutu. |
||||
|
||||
Sygnatura metody obsługującej to zdarzenie powinna wyglądać następująco: |
||||
|
||||
```javascript |
||||
function (event, attribute, messages, deferreds) |
||||
``` |
||||
|
||||
gdzie |
||||
|
||||
- `event`: obiekt Event. |
||||
- `attribute`: atrybut poddawany walidacji. Sprawdź konstrukcję `attributeDefaults`, aby dowiedzieć się więcej o strukturze tego parametru. |
||||
- `messages`: tablica, do której możesz dodać opisy błędów walidacji dla wybranego atrybutu. |
||||
- `deferreds`: tablica obiektów kolejki. Możesz użyć `deferreds.add(callback)`, aby dodać nową walidację do kolejki. |
||||
|
||||
Jeśli metoda obsługująca zwróci boolean `false`, zatrzyma dalszą walidację wybranego atrybutu. W takim wypadku zdarzenie |
||||
`afterValidateAttribute` nie będzie już wyzwalane. |
||||
|
||||
### `afterValidateAttribute` |
||||
|
||||
`afterValidateAttribute` jest wyzwalane po walidacji całego formularza i każdego atrybutu. |
||||
|
||||
Sygnatura metody obsługującej to zdarzenie powinna wyglądać następująco: |
||||
|
||||
```javascript |
||||
function (event, attribute, messages) |
||||
``` |
||||
|
||||
gdzie |
||||
|
||||
- `event`: obiekt Event. |
||||
- `attribute`: atrybut poddawany walidacji. Sprawdź konstrukcję `attributeDefaults`, aby dowiedzieć się więcej o strukturze tego parametru. |
||||
- `messages`: tablica, do której możesz dodać opisy błędów walidacji dla wybranego atrybutu. |
||||
|
||||
### `beforeSubmit` |
||||
|
||||
`beforeSubmit` jest wyzwalane przed wysłaniem formularza, po pomyślnej walidacji. |
||||
|
||||
Sygnatura metody obsługującej to zdarzenie powinna wyglądać następująco: |
||||
|
||||
```javascript |
||||
function (event) |
||||
``` |
||||
|
||||
gdzie event jest obiektem Event. |
||||
|
||||
Jeśli metoda obsługująca zwróci boolean `false`, zatrzyma wysyłanie formularza. |
||||
|
||||
### `ajaxBeforeSend` |
||||
|
||||
`ajaxBeforeSend` jest wyzwalane przed wysłaniem żądania AJAX w przypadku walidacji AJAX-owej. |
||||
|
||||
Sygnatura metody obsługującej to zdarzenie powinna wyglądać następująco: |
||||
|
||||
```javascript |
||||
function (event, jqXHR, settings) |
||||
``` |
||||
|
||||
gdzie |
||||
|
||||
- `event`: obiekt Event. |
||||
- `jqXHR`: obiekt jqXHR. |
||||
- `settings`: konfiguracja żądania AJAX. |
||||
|
||||
### `ajaxComplete` |
||||
|
||||
`ajaxComplete` jest wyzwalane po ukończeniu żądania AJAX w przypadku walidacji AJAX-owej. |
||||
|
||||
Sygnatura metody obsługującej to zdarzenie powinna wyglądać następująco: |
||||
|
||||
```javascript |
||||
function (event, jqXHR, textStatus) |
||||
``` |
||||
|
||||
gdzie |
||||
|
||||
- `event`: obiekt Event. |
||||
- `jqXHR`: obiekt jqXHR. |
||||
- `textStatus`: status żądania ("success", "notmodified", "error", "timeout", "abort" lub "parsererror"). |
||||
|
||||
## Wysyłanie formularza za pomocą AJAX |
||||
|
||||
Walidacja może być przeprowadzona po stronie klienta lub za pomocą AJAX-a, ale wysyłanie formularza jest domyślnie przeprowadzane |
||||
za pomocą zwyczajnego żądania. Jeśli chcesz przesłać formularz za pomocą AJAX, możesz to zrobić obsługując zdarzenie `beforeSubmit` |
||||
formularza w następujący sposób: |
||||
|
||||
```javascript |
||||
var $form = $('#formId'); |
||||
$form.on('beforeSubmit', function() { |
||||
var data = $form.serialize(); |
||||
$.ajax({ |
||||
url: $form.attr('action'), |
||||
type: 'POST', |
||||
data: data, |
||||
success: function (data) { |
||||
// Implementacja pomyślnego statusu |
||||
}, |
||||
error: function(jqXHR, errMsg) { |
||||
alert(errMsg); |
||||
} |
||||
}); |
||||
return false; // powstrzymuje przed domyślnym sposobem wysłania |
||||
}); |
||||
``` |
||||
|
||||
Aby dowiedzieć się więcej o funkcji jQuery `ajax()`, zapoznaj się z [dokumentacją jQuery](https://api.jquery.com/jQuery.ajax/). |
||||
|
||||
|
||||
## Dynamiczne dodawanie pól |
||||
|
||||
We współczesnych aplikacjach webowych często koniecznie jest modyfikowanie formularza już po tym, jak został zaprezentowany użytkownikowi. |
||||
Dla przykładu może to być dodawanie nowego pola po kliknięciu w ikonę "z plusem". |
||||
Aby uruchomić walidację takich pól, należy je zarejestrować za pomocą JavaScriptowego pluginu ActiveForm. |
||||
|
||||
Po dodaniu pola do formularza, należy dołączyć je również do listy walidacji: |
||||
|
||||
```javascript |
||||
$('#contact-form').yiiActiveForm('add', { |
||||
id: 'address', |
||||
name: 'address', |
||||
container: '.field-address', |
||||
input: '#address', |
||||
error: '.help-block', |
||||
validate: function (attribute, value, messages, deferred, $form) { |
||||
yii.validation.required(value, messages, {message: "Informacja dotycząca walidacji tutaj"}); |
||||
} |
||||
}); |
||||
``` |
||||
|
||||
Aby usunąć pole z listy walidacji (aby nie było już sprawdzane), możesz wykonać następujący kod: |
||||
|
||||
```javascript |
||||
$('#contact-form').yiiActiveForm('remove', 'address'); |
||||
``` |
@ -0,0 +1,209 @@
|
||||
# Używanie Yii jako mikroframeworka |
||||
|
||||
Yii może być z powodzeniem wykorzystywane bez dodatkowych funkcjonalności dostarczanych przez prosty i zaawansowany szablon aplikacji. Inaczej mówiąc, |
||||
Yii już jest samo w sobie mikroframeworkiem. Do pracy z Yii nie jest wymagane, aby struktura folderów była dokładnie taka, jak pokazana w szablonach. |
||||
|
||||
Jest to szczególnie korzystne, kiedy nie potrzebujesz gotowego kodu szablonów, jak w przypadku assetów luc widoków. Jednym z takich przypadków jest budowa JSON API. |
||||
W tej sekcji pokażemy jak to zrobić. |
||||
|
||||
## Instalacja Yii |
||||
|
||||
Stwórz folder dla plików swojego projektu i ustaw go jako aktywną ścieżkę. Komendy używane w przykładach oparte są na składni UNIXowej, ale podobne dostępne są również w Windows. |
||||
|
||||
```bash |
||||
mkdir micro-app |
||||
cd micro-app |
||||
``` |
||||
|
||||
> Note: minimalna wiedza na temat użytkowania Composera jest wymagana w celu kontynuacji. Jeśli nie wiesz, jak używać Composera, prosimy o zapoznanie się najpierw z [Przewodnikiem po Composerze](https://getcomposer.org/doc/00-intro.md). |
||||
|
||||
Stwórz plik `composer.json` w folderze `micro-app`, używając swojego ulubionego edytora i dodaj co następuje: |
||||
|
||||
```json |
||||
{ |
||||
"require": { |
||||
"yiisoft/yii2": "~2.0.0" |
||||
}, |
||||
"repositories": [ |
||||
{ |
||||
"type": "composer", |
||||
"url": "https://asset-packagist.org" |
||||
} |
||||
] |
||||
} |
||||
``` |
||||
|
||||
Zapisz plik i uruchom komendę `composer install`. Dzięki temu zainstalujesz framework i wszystkie jego zależności. |
||||
|
||||
## Tworzenie struktury projektu |
||||
|
||||
Po zainstalowaniu frameworka, czas na utworzenie [punktu wejścia](structure-entry-scripts.md) dla aplikacji. Punkt wejścia to pierwszy plik, który będzie uruchamiany, |
||||
podczas startu aplikacji. Ze względów bezpieczeństwa, zalecane jest, aby plik punktu wejścia umieścić w osobnym folderze, który będzie ustawiony jako bazowy folder aplikacji. |
||||
|
||||
Stwórz folder `web` i umieść w nim plik `index.php` z następującą zawartością: |
||||
|
||||
```php |
||||
<?php |
||||
|
||||
// zakomentuj poniższe dwie linie przy wydaniu aplikacji na środowisku produkcyjnym |
||||
defined('YII_DEBUG') or define('YII_DEBUG', true); |
||||
defined('YII_ENV') or define('YII_ENV', 'dev'); |
||||
|
||||
require(__DIR__ . '/../vendor/autoload.php'); |
||||
require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php'); |
||||
|
||||
$config = require __DIR__ . '/../config.php'; |
||||
(new yii\web\Application($config))->run(); |
||||
``` |
||||
|
||||
Stwórz również plik `config.php`, który będzie zawierał całą konfigurację aplikacji: |
||||
|
||||
```php |
||||
<?php |
||||
return [ |
||||
'id' => 'micro-app', |
||||
// ścieżką bazową aplikacji będzie folder `micro-app` |
||||
'basePath' => __DIR__, |
||||
// w tym miejscu określamy, gdzie aplikacja ma szukać wszystkich kontrolerów |
||||
'controllerNamespace' => 'micro\controllers', |
||||
// ustawiamy alias, aby umożliwić autoładowanie klas z przestrzeni nazw 'micro' |
||||
'aliases' => [ |
||||
'@micro' => __DIR__, |
||||
], |
||||
]; |
||||
``` |
||||
|
||||
> Info: Pomimo że konfiguracja mogłaby być przechowywana w pliku `index.php`, zalecane jest, aby zapisana była osobno. |
||||
> Dzięki temu może być również wykorzystywana dla aplikacji konsolowej, jak pokazano to poniżej. |
||||
|
||||
Twój projekt jest już gotowy do rozpoczęcia kodowania. Od Ciebie również zależy struktura jego folderów, dopóki jak będziesz pamiętać o poprawnych przestrzeniach nazw. |
||||
|
||||
## Tworzenie pierwszego kontrolera |
||||
|
||||
Stwórz folder `controllers` i dodaj w nim plik `SiteController.php`, który będzie domyślnym kontrolerem obsługującym żądania bez wskazanej wyraźnie ścieżki. |
||||
|
||||
```php |
||||
<?php |
||||
|
||||
namespace micro\controllers; |
||||
|
||||
use yii\web\Controller; |
||||
|
||||
class SiteController extends Controller |
||||
{ |
||||
public function actionIndex() |
||||
{ |
||||
return 'Hello World!'; |
||||
} |
||||
} |
||||
``` |
||||
|
||||
Jeśli chcesz użyć innej nazwy dla tego kontrolera, nie krępuj się - musisz jedynie skonfigurować odpowiednio [[yii\base\Application::$defaultRoute]]. |
||||
Dla przykładu, jeśli chcesz go zmienić na `DefaultController`, ustaw `'defaultRoute' => 'default/index'` w konfiguracji. |
||||
|
||||
W tym momencie struktura projektu powinna wyglądać jak poniżej: |
||||
|
||||
``` |
||||
micro-app/ |
||||
├── composer.json |
||||
├── web/ |
||||
└── index.php |
||||
└── controllers/ |
||||
└── SiteController.php |
||||
``` |
||||
|
||||
Jeśli nie ustawiłeś jeszcze serwera web, być może zechcesz zerknąć na [pliki przykładów konfiguracji serwera web](start-installation.md#configuring-web-servers). |
||||
Inną opcją jest skorzystanie z komendy `yii serve`, która użyje wbudowanego w PHP serwera web. Możesz uruchomić ją z poziomu folderu `micro-app/` za pomocą: |
||||
|
||||
vendor/bin/yii serve --docroot=./web |
||||
|
||||
Uruchomienie adresu URL aplikacji w przeglądarce powinno zaowocować teraz komunikatem "Hello World!", który jest zwracany w `SiteController::actionIndex()`. |
||||
|
||||
> Info: W naszym przykładzie zmieniliśmy domyślną przestrzeń nazw aplikacji `app` na `micro`, aby zademonstrować, |
||||
> że nie ma potrzeby być ograniczonym przez tę nazwę (w przypadku, gdyby ktoś myślał, że jednak jest). Po zmianie jej na inną, |
||||
> należy jedynie zmodyfikować odpowiednio [[yii\base\Application::$controllerNamespace|przestrzeń nazw kontrolerów]] i ustawić właściwy alias. |
||||
|
||||
|
||||
## Tworzenie API REST |
||||
|
||||
Aby zademonstrować, jak korzystać z naszego "mikroframeworka", stworzymy proste API REST dla postów. |
||||
|
||||
Aby API mogło zwrócić jakieś dane, najpierw potrzebujemy ich bazy. Dodaj konfigurację połączenia z bazą danych do konfiguracji aplikacji: |
||||
|
||||
```php |
||||
'components' => [ |
||||
'db' => [ |
||||
'class' => 'yii\db\Connection', |
||||
'dsn' => 'sqlite:@micro/database.sqlite', |
||||
], |
||||
], |
||||
``` |
||||
|
||||
> Info: Używamy w tym przykładzie bazy danych sqlite dla uproszczenia. Aby zapoznać się z innymi opcjami, przejdź do [przewodnika po bazach danych](db-dao.md). |
||||
|
||||
Następnie tworzymy [migrację bazodanową](db-migrations.md), aby skonstruować tabelę postów. |
||||
Upewnij się, że posiadasz oddzielny plik konfiguracji, jak zostało to opisane powyżej, ponieważ musimy teraz uruchomić komendę konsolową, jak poniżej. |
||||
Uruchomienie tych komend utworzy plik migracji i wprowadzi migrację do bazy danych: |
||||
|
||||
vendor/bin/yii migrate/create --appconfig=config.php create_post_table --fields="title:string,body:text" |
||||
vendor/bin/yii migrate/up --appconfig=config.php |
||||
|
||||
Stwórz folder `models` i plik `Post.php` w tym folderze. Poniżej znajdziesz kod dla modelu: |
||||
|
||||
```php |
||||
<?php |
||||
|
||||
namespace micro\models; |
||||
|
||||
use yii\db\ActiveRecord; |
||||
|
||||
class Post extends ActiveRecord |
||||
{ |
||||
public static function tableName() |
||||
{ |
||||
return '{{posts}}'; |
||||
} |
||||
} |
||||
``` |
||||
|
||||
> Info: Tak utworzony model jest klasą ActiveRecord, która reprezentuje dane z tabeli `posts`. |
||||
> Zapoznaj się z [przewodnikiem po active record](db-active-record.md), aby uzyskać więcej informacji. |
||||
|
||||
Aby obsłużyć posty w naszym API, dodaj `PostController` w `controllers`: |
||||
|
||||
```php |
||||
<?php |
||||
|
||||
namespace micro\controllers; |
||||
|
||||
use yii\rest\ActiveController; |
||||
|
||||
class PostController extends ActiveController |
||||
{ |
||||
public $modelClass = 'micro\models\Post'; |
||||
|
||||
public function behaviors() |
||||
{ |
||||
// wyłącz rateLimiter, który do pracy wymaga, aby użytkownik był zalogowany |
||||
$behaviors = parent::behaviors(); |
||||
unset($behaviors['rateLimiter']); |
||||
return $behaviors; |
||||
} |
||||
} |
||||
``` |
||||
|
||||
W tym momencie nasze API obsługuje już następujące adresy URL: |
||||
|
||||
- `/index.php?r=post` - wyświetla listę wszystkich postów |
||||
- `/index.php?r=post/view&id=1` - wyświetla post o ID 1 |
||||
- `/index.php?r=post/create` - tworzy post |
||||
- `/index.php?r=post/update&id=1` - aktualizuje post o ID 1 |
||||
- `/index.php?r=post/delete&id=1` - usuwa post o ID 1 |
||||
|
||||
Zapoznaj się z poniższymi wskazówkami, które pomogą Ci w dalszym rozwijaniu Twojej aplikacji: |
||||
|
||||
- Aktualnie API rozpoznaje jedynie urlenkodowane dane formularza na wejściu - aby zmienić je w prawdziwe JSON API, |
||||
musisz skonfigurować [[yii\web\JsonParser]]. |
||||
- Aby uczynić adresy URL, bardziej przyjaznymi dla użytkownika, musisz skonfigurować ruting. |
||||
Zobacz [przewodnik po rutingu REST](rest-routing.md), który wyjaśnia, jak to zrobić. |
||||
- Dodatkowo przeczytaj też sekcję [Dalsze kroki](start-looking-ahead.md), która podpowie jak zaplanować rozwój projektu. |
@ -1,11 +1,16 @@
|
||||
Приёмочное тестирование |
||||
======================= |
||||
|
||||
> Note: Данный раздел находится в разработке. |
||||
Приемочный тест проверяет сценарий с точки зрения конечного пользователя. К тестируемому приложению получают доступ либо через PhpBrowser, либо через реальный браузер. В обоих случаях браузеры взаимодействуют с приложением через HTTP, поэтому приложение следует запускать посредством веб-сервера. |
||||
|
||||
Приемочное тестирование реализуется с помощью фреймворка Codeception, который имеет отличную документацию: |
||||
|
||||
- [Codeception for Yii framework](http://codeception.com/for/yii) |
||||
- [Codeception Acceptance Tests](http://codeception.com/docs/03-AcceptanceTests) |
||||
|
||||
Запуск тестов в шаблонах проектов basic и advanced |
||||
-------------------------------------------------- |
||||
|
||||
Инструкции приведены в `apps/advanced/tests/README.md` и `apps/basic/tests/README.md`. |
||||
Если вы начали с шаблона advanced, пожалуйста, обратитесь к руководству по ["Тестированию"](https://github.com/yiisoft/yii2-app-advanced/blob/master/docs/guide/start-testing.md) для получения более детальной информации о запускаемых тестах. |
||||
|
||||
Если вы начали с шаблона basic, обратитесь к разделу ["Тестирование"](https://github.com/yiisoft/yii2-app-basic/blob/master/README.md#testing) в его README. |
||||
|
@ -0,0 +1,206 @@
|
||||
# Использование Yii в качестве микро-framework'а |
||||
|
||||
Yii можно легко использовать без функций включенных в базовый и расширенный шаблоны приложений. Другими словами Yii уже является микро-каркасом. Не требуется иметь структуру каталогов предоставляемую этими шаблонами при работе с Yii. |
||||
|
||||
Это особенно удобно, когда Вам не нужен весь пред-установленный шаблонный код, такой как `Assets` или `Views`. Одним из таких случаев является создание JSON API. В следующих разделах будет показано, как это сделать. |
||||
|
||||
## Установка Yii |
||||
|
||||
Создайте каталог для файлов проекта и смените рабочий каталог на этот путь. В примерах используются команды Unix, но аналогичные команды существуют и в Windows. |
||||
|
||||
```bash |
||||
mkdir micro-app |
||||
cd micro-app |
||||
``` |
||||
|
||||
> Note: Для продолжения требуется немного знаний о Composer. Если Вы еще не знаете, как использовать Composer, пожалуйста, найдите время, чтобы прочитать [Руководство Composer](https://getcomposer.org/doc/00-intro.md). |
||||
|
||||
Создайте файл `composer.json` в каталоге `micro-app` с помощью Вашего любимого редактора и добавьте следующее: |
||||
|
||||
```json |
||||
{ |
||||
"require": { |
||||
"yiisoft/yii2": "~2.0.0" |
||||
}, |
||||
"repositories": [ |
||||
{ |
||||
"type": "composer", |
||||
"url": "https://asset-packagist.org" |
||||
} |
||||
] |
||||
} |
||||
``` |
||||
|
||||
Сохраните файл и запустите команду `comper install`. Это установит framework со всеми его зависимостями. |
||||
|
||||
## Создание структуры проекта |
||||
|
||||
После того как Вы установили фреймворк, пришло время создать [входную точку](structure-entry-scripts.md) приложения. Точка входа - это самый первый файл, который будет выполнен при попытке открыть приложение. По соображениям безопасности рекомендуется поместить файл точки входа в отдельный каталог и сделать каталог корнем веб директории. |
||||
|
||||
Создайте каталог `web` и поместите в него файл `index.php` со следующим содержимым: |
||||
|
||||
```php |
||||
<?php |
||||
|
||||
// закомментируйте следующие две строки при использовании в рабочем режиме |
||||
defined('YII_DEBUG') or define('YII_DEBUG', true); |
||||
defined('YII_ENV') or define('YII_ENV', 'dev'); |
||||
|
||||
require(__DIR__ . '/../vendor/autoload.php'); |
||||
require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php'); |
||||
|
||||
$config = require __DIR__ . '/../config.php'; |
||||
(new yii\web\Application($config))->run(); |
||||
``` |
||||
|
||||
Также создайте файл с именем `config.php`, который будет содержать всю конфигурацию приложения: |
||||
|
||||
```php |
||||
<?php |
||||
return [ |
||||
'id' => 'micro-app', |
||||
// basePath (базовый путь) приложения будет каталог `micro-app` |
||||
'basePath' => __DIR__, |
||||
// это пространство имен где приложение будет искать все контроллеры |
||||
'controllerNamespace' => 'micro\controllers', |
||||
// установим псевдоним '@micro', чтобы включить автозагрузку классов из пространства имен 'micro' |
||||
'aliases' => [ |
||||
'@micro' => __DIR__, |
||||
], |
||||
]; |
||||
``` |
||||
|
||||
> Info: Несмотря на то, что конфигурация приложения может находиться в файле `index.php` рекомендуется |
||||
> содержать её в отдельном файле. Таким образом её можно также использовать и для консольного приложения, как показано ниже. |
||||
|
||||
Теперь Ваш проект готов к наполнению кодом. Вам решать какую структуру каталогов проекта Вы выберите, пока Вы сможете видеть пространства имен. |
||||
|
||||
## Создание первого контроллера |
||||
|
||||
Создайте каталог `controllers` и добавьте туда файл `SiteController.php` который является контроллером по умолчанию, он будет обрабатывать запрос без пути. |
||||
|
||||
```php |
||||
<?php |
||||
|
||||
namespace micro\controllers; |
||||
|
||||
use yii\web\Controller; |
||||
|
||||
class SiteController extends Controller |
||||
{ |
||||
public function actionIndex() |
||||
{ |
||||
return 'Hello World!'; |
||||
} |
||||
} |
||||
``` |
||||
|
||||
Если Вы хотите использовать другое имя для этого контроллера, Вы можете изменить его настроив [[yii\base\Application::$defaultRoute]]. |
||||
Например для `DefaultController` будет соответственно `'defaultRoute' => 'default/index'`. |
||||
|
||||
На данный момент структура проекта должна выглядеть так: |
||||
|
||||
``` |
||||
micro-app/ |
||||
├── composer.json |
||||
├── web/ |
||||
└── index.php |
||||
└── controllers/ |
||||
└── SiteController.php |
||||
``` |
||||
|
||||
Если Вы еще не настроили веб-сервер, Вы можете взглянуть на [примеры конфигурационных файлов веб-серверов](start-installation.md#Настройка-веб-сервера-). |
||||
Другой возможностью является использование команды `yii serve` которая будет использовать встроенный веб-сервер PHP. Вы можете запустить её из каталога `micro-app/` через: |
||||
|
||||
vendor/bin/yii serve --docroot=./web |
||||
|
||||
При открытии URL приложения в браузере, он теперь должен печатать "Hello World!" который был возвращен из `SiteController::actionIndex()`. |
||||
|
||||
> Info: В нашем примере мы изменили пространство имен по умолчанию приложения с `app` на` micro`, чтобы продемонстрировать |
||||
> что Вы не привязаны к этому имени (в случае, если Вы считали, что это так), а затем скорректировали |
||||
> [[yii\base\Application::$controllerNamespace|controllers namespace]] и установили правильный псевдоним. |
||||
|
||||
## Создание REST API |
||||
|
||||
Чтобы продемонстрировать использование нашей "микроархитектуры" мы создадим простой REST API для сообщений. |
||||
|
||||
Чтобы этот API обслуживал некоторые данные, нам нужна база данных. Добавим конфигурацию подключения базы данных |
||||
к конфигурации приложения: |
||||
|
||||
```php |
||||
'components' => [ |
||||
'db' => [ |
||||
'class' => 'yii\db\Connection', |
||||
'dsn' => 'sqlite:@micro/database.sqlite', |
||||
], |
||||
], |
||||
``` |
||||
|
||||
> Info: Для простоты мы используем базу данных sqlite. Дополнительную информацию см. в [Руководство по базам данных](db-dao.md). |
||||
|
||||
Затем мы создаем [миграции базы данных](db-migrations.md) для создания таблицы сообщений. |
||||
Убедитесь, что у Вас есть отдельный файл конфигурации, как описано выше, нам это нужно для того, чтобы запустить консольные команды описанные ниже. |
||||
Запуск следующих команд создаст файл миграции базы данных и применит миграцию к базе данных: |
||||
|
||||
vendor/bin/yii migrate/create --appconfig=config.php create_post_table --fields="title:string,body:text" |
||||
vendor/bin/yii migrate/up --appconfig=config.php |
||||
|
||||
Создайте каталог `models` и файл` Post.php` в этом каталоге. Это код модели: |
||||
|
||||
```php |
||||
<?php |
||||
|
||||
namespace micro\models; |
||||
|
||||
use yii\db\ActiveRecord; |
||||
|
||||
class Post extends ActiveRecord |
||||
{ |
||||
public static function tableName() |
||||
{ |
||||
return '{{posts}}'; |
||||
} |
||||
} |
||||
``` |
||||
|
||||
> Info: Созданная модель представляет собой класс ActiveRecord, который представляет данные из таблицы `posts`. |
||||
> Для получения дополнительной информации обратитесь к [active record руководству](db-active-record.md). |
||||
|
||||
Чтобы обслуживать сообщения в нашем API, добавьте `PostController` в` controllers`: |
||||
|
||||
```php |
||||
<?php |
||||
|
||||
namespace micro\controllers; |
||||
|
||||
use yii\rest\ActiveController; |
||||
|
||||
class PostController extends ActiveController |
||||
{ |
||||
public $modelClass = 'micro\models\Post'; |
||||
|
||||
public function behaviors() |
||||
{ |
||||
// удаляем rateLimiter, требуется для аутентификации пользователя |
||||
$behaviors = parent::behaviors(); |
||||
unset($behaviors['rateLimiter']); |
||||
return $behaviors; |
||||
} |
||||
} |
||||
``` |
||||
|
||||
На этом этапе наш API предоставляет следующие URL-адреса: |
||||
|
||||
- `/index.php?r=post` - список всех сообщений |
||||
- `/index.php?r=post/view&id=1` - просмотр сообщения с ID 1 |
||||
- `/index.php?r=post/create` - создание сообщения |
||||
- `/index.php?r=post/update&id=1` - обновление сообщения with ID 1 |
||||
- `/index.php?r=post/delete&id=1` - удаление сообщения with ID 1 |
||||
|
||||
Начиная с этого момента Вы можете посмотреть следующие руководства для дальнейшего развития своего приложения: |
||||
|
||||
- API в настоящий момент понимает только данные urlencoded как входные данные, чтобы сделать его настоящим JSON API, Вам |
||||
необходимо настроить [[yii\web\JsonParser]]. |
||||
- Чтобы сделать URL более дружественным, вам необходимо настроить маршрутизацию. |
||||
См. [Руководство по маршрутизации REST](rest-routing.md) о том, как это сделать. |
||||
- Дополнительную информацию см. в разделе [Взгляд в будущее](start-looking-ahead.md). |
@ -0,0 +1,22 @@
|
||||
# What do you need to know |
||||
|
||||
Yii learning curve is not as steep as other PHP frameworks but still it requires some beforehand knowledge. |
||||
|
||||
## PHP |
||||
|
||||
Yii is a PHP framework so make sure you [read and understand language reference](http://php.net/manual/en/langref.php). |
||||
|
||||
## Object oriented programming |
||||
|
||||
Basic understanding of object oriented programming is required. If you're not familiar with it, check one of the many |
||||
tutorials available such as [the one from tuts+](https://code.tutsplus.com/tutorials/object-oriented-php-for-beginners--net-12762). |
||||
|
||||
Note that the more complicated your application is the more advanced OOP concepts your should learn in order to successfully |
||||
manage that complexity. |
||||
|
||||
## Command line and composer |
||||
|
||||
Yii extensively uses de-facto standard PHP package manager, [Composer](https://getcomposer.org/) so make sure you read |
||||
and understand its guide. If you are not familiar with using command line it is time to start trying. Once you'll |
||||
learn the basics you'll never want to work without it. |
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue