Skip to content
8 changes: 2 additions & 6 deletions cookbook/en/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,6 @@ This book conforms to the [Terms of Yii Documentation](https://www.yiiframework.

---

[Preface](preface.md)

## Getting started

## Organizing code

- [Preface](preface.md)
- [Structuring code by use-case with vertical slices](organizing-code/structuring-by-use-case-with-vertical-slices.md)
- [Sentry integration](sentry-integration.md)
4 changes: 2 additions & 2 deletions cookbook/en/preface.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@

Yii is a high-performance, package-based PHP framework for developing modern applications.
The name Yii (pronounced `Yee` or `[ji:]`) means "simple and evolutionary" in Chinese.
You can also think about it as an acronym for **Yes It Is**!

Check failure on line 5 in cookbook/en/preface.md

View workflow job for this annotation

GitHub Actions / vale

[vale] cookbook/en/preface.md#L5

[Microsoft.Contractions] Use 'it's' instead of 'It Is'.
Raw output
{"message": "[Microsoft.Contractions] Use 'it's' instead of 'It Is'.", "location": {"path": "cookbook/en/preface.md", "range": {"start": {"line": 5, "column": 53}}}, "severity": "ERROR"}

Yii is a generic Web programming framework.
You can use it for developing all kinds of Web applications using PHP.
Because of its architecture and sophisticated caching support,
it's especially suitable for developing large-scale applications such as portals, content management systems,
e-commerce, REST APIs, etc.

Check notice on line 11 in cookbook/en/preface.md

View workflow job for this annotation

GitHub Actions / vale

[vale] cookbook/en/preface.md#L11

[Microsoft.Acronyms] 'REST' has no definition.
Raw output
{"message": "[Microsoft.Acronyms] 'REST' has no definition.", "location": {"path": "cookbook/en/preface.md", "range": {"start": {"line": 11, "column": 13}}}, "severity": "INFO"}

Together with a comprehensive set of documentation and an enthusiastic user community, Yii can reduce your development
time in the long run significantly compared with other frameworks.
time in a long run significantly.

## What's the book about

Expand All @@ -24,7 +24,7 @@

## Prerequisites

- You should have Yii 3.0 installed.
- You should have Yii3 installed.
- You should be familiar with the framework basics and the official guide.

## How to participate
Expand Down
117 changes: 117 additions & 0 deletions cookbook/en/sentry-integration.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
# Sentry integration

## What is Sentry

Check notice on line 3 in cookbook/en/sentry-integration.md

View workflow job for this annotation

GitHub Actions / vale

[vale] cookbook/en/sentry-integration.md#L3

[Microsoft.Headings] 'What is Sentry' should use sentence-style capitalization.
Raw output
{"message": "[Microsoft.Headings] 'What is Sentry' should use sentence-style capitalization.", "location": {"path": "cookbook/en/sentry-integration.md", "range": {"start": {"line": 3, "column": 4}}}, "severity": "INFO"}

Check failure on line 3 in cookbook/en/sentry-integration.md

View workflow job for this annotation

GitHub Actions / vale

[vale] cookbook/en/sentry-integration.md#L3

[Microsoft.Contractions] Use 'what's' instead of 'What is'.
Raw output
{"message": "[Microsoft.Contractions] Use 'what's' instead of 'What is'.", "location": {"path": "cookbook/en/sentry-integration.md", "range": {"start": {"line": 3, "column": 4}}}, "severity": "ERROR"}

[Sentry](https://sentry.io/) is a tool for monitoring and debugging application stability and performance.
Sentry gives you access to the events that you send there from your application.

Most often, Sentry is used for monitoring errors (exceptions).

Check notice on line 8 in cookbook/en/sentry-integration.md

View workflow job for this annotation

GitHub Actions / vale

[vale] cookbook/en/sentry-integration.md#L8

[Microsoft.Passive] 'is used' looks like passive voice.
Raw output
{"message": "[Microsoft.Passive] 'is used' looks like passive voice.", "location": {"path": "cookbook/en/sentry-integration.md", "range": {"start": {"line": 8, "column": 20}}}, "severity": "INFO"}
You can enrich errors with context to better understand the problem:
- Request arguments
- Tags for grouping exceptions
- Environment state: environment variables, application state, and other global attributes

You can find the full list of features on the official website: https://sentry.io/welcome/

## Installation

### Install the package

Install the required package `yiisoft/yii-sentry` with the following command:

```shell
composer require yiisoft/yii-sentry --prefer-dist
```

### Install an HTTP driver

Check notice on line 26 in cookbook/en/sentry-integration.md

View workflow job for this annotation

GitHub Actions / vale

[vale] cookbook/en/sentry-integration.md#L26

[Microsoft.Headings] 'Install an HTTP driver' should use sentence-style capitalization.
Raw output
{"message": "[Microsoft.Headings] 'Install an HTTP driver' should use sentence-style capitalization.", "location": {"path": "cookbook/en/sentry-integration.md", "range": {"start": {"line": 26, "column": 5}}}, "severity": "INFO"}

Check warning on line 26 in cookbook/en/sentry-integration.md

View workflow job for this annotation

GitHub Actions / vale

[vale] cookbook/en/sentry-integration.md#L26

[Microsoft.HeadingAcronyms] Avoid using acronyms in a title or heading.
Raw output
{"message": "[Microsoft.HeadingAcronyms] Avoid using acronyms in a title or heading.", "location": {"path": "cookbook/en/sentry-integration.md", "range": {"start": {"line": 26, "column": 16}}}, "severity": "WARNING"}

The [`getsentry/sentry-php`](https://github.com/getsentry/sentry-php) library requires the `php-http/httplug` package and any HTTP driver.
In the example below we’ll use the Guzzle adapter.

Check warning on line 29 in cookbook/en/sentry-integration.md

View workflow job for this annotation

GitHub Actions / vale

[vale] cookbook/en/sentry-integration.md#L29

[Microsoft.We] Try to avoid using first-person plural like 'we'.
Raw output
{"message": "[Microsoft.We] Try to avoid using first-person plural like 'we'.", "location": {"path": "cookbook/en/sentry-integration.md", "range": {"start": {"line": 29, "column": 22}}}, "severity": "WARNING"}

> You can find the list of all adapters on [this page](https://docs.php-http.org/en/latest/clients.html#clients-adapters).

To install the packages, run the following command:

```shell
composer require php-http/httplug php-http/guzzle7-adapter --prefer-dist
```

## Configuration

### Get and store the token

Next, configure the application.

First, register at [Sentry](https://sentry.io) and create a project.

Then, in the project settings on the “General Settings” tab, find the “Security Token” field and copy its value.

Now put this token into the package configuration. By default, the config is located at `config/packages/yiisoft/yii-sentry/config/params.php`.

Check notice on line 49 in cookbook/en/sentry-integration.md

View workflow job for this annotation

GitHub Actions / vale

[vale] cookbook/en/sentry-integration.md#L49

[Microsoft.Passive] 'is located' looks like passive voice.
Raw output
{"message": "[Microsoft.Passive] 'is located' looks like passive voice.", "location": {"path": "cookbook/en/sentry-integration.md", "range": {"start": {"line": 49, "column": 75}}}, "severity": "INFO"}
Set the copied token as the value of the array element at `yiisoft/yii-sentry` => `options` => `dsn`. Example:

```diff
'yiisoft/yii-sentry' => [
'enabled' => true,
'options' => [
- 'dsn' => '',
+ 'dsn' => 'TOKEN',
],
],
```

### Configure the HTTP client

Check notice on line 62 in cookbook/en/sentry-integration.md

View workflow job for this annotation

GitHub Actions / vale

[vale] cookbook/en/sentry-integration.md#L62

[Microsoft.Headings] 'Configure the HTTP client' should use sentence-style capitalization.
Raw output
{"message": "[Microsoft.Headings] 'Configure the HTTP client' should use sentence-style capitalization.", "location": {"path": "cookbook/en/sentry-integration.md", "range": {"start": {"line": 62, "column": 5}}}, "severity": "INFO"}

Check warning on line 62 in cookbook/en/sentry-integration.md

View workflow job for this annotation

GitHub Actions / vale

[vale] cookbook/en/sentry-integration.md#L62

[Microsoft.HeadingAcronyms] Avoid using acronyms in a title or heading.
Raw output
{"message": "[Microsoft.HeadingAcronyms] Avoid using acronyms in a title or heading.", "location": {"path": "cookbook/en/sentry-integration.md", "range": {"start": {"line": 62, "column": 19}}}, "severity": "WARNING"}

After installing the HTTP client, configure it.

Create the file `config/common/sentry.php` and put the following code into it:

```php
<?php

declare(strict_types=1);

return [
\Http\Client\HttpClient::class => \GuzzleHttp\Client::class,
\Http\Client\HttpAsyncClient::class => [
'class' => \Http\Adapter\Guzzle7\Client::class,
'__construct()' => [
\Yiisoft\Factory\Definition\Reference::to(\Http\Client\HttpClient::class),
],
],
];
```

# Integration

### Web

Sentry support for `web` is implemented as middleware.

Check notice on line 88 in cookbook/en/sentry-integration.md

View workflow job for this annotation

GitHub Actions / vale

[vale] cookbook/en/sentry-integration.md#L88

[Microsoft.Passive] 'is implemented' looks like passive voice.
Raw output
{"message": "[Microsoft.Passive] 'is implemented' looks like passive voice.", "location": {"path": "cookbook/en/sentry-integration.md", "range": {"start": {"line": 88, "column": 26}}}, "severity": "INFO"}

That means you only need to add `SentryMiddleware` to the global middleware list in `config/web/application.php`:

```diff
return [
Yiisoft\Yii\Web\Application::class => [
'__construct()' => [
'dispatcher' => DynamicReference::to(static function (Injector $injector) {
return ($injector->make(MiddlewareDispatcher::class))
->withMiddlewares(
[
Router::class,
SubFolder::class,
+ SentryMiddleware::class,
ErrorCatcher::class,
]
);
}),
'fallbackHandler' => Reference::to(NotFoundHandler::class),
],
],
];
```

### Console

Sentry supports `console` via a handler for the [ConsoleEvents::ERROR](https://symfony.com/doc/current/components/console/events.html#the-consoleevents-error-event) event.

Check notice on line 115 in cookbook/en/sentry-integration.md

View workflow job for this annotation

GitHub Actions / vale

[vale] cookbook/en/sentry-integration.md#L115

[Microsoft.Acronyms] 'ERROR' has no definition.
Raw output
{"message": "[Microsoft.Acronyms] 'ERROR' has no definition.", "location": {"path": "cookbook/en/sentry-integration.md", "range": {"start": {"line": 115, "column": 65}}}, "severity": "INFO"}

The package provides a configuration file that automatically subscribes the application to this event.
13 changes: 13 additions & 0 deletions cookbook/ru/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Книга рецептов Yii3

Check notice on line 1 in cookbook/ru/README.md

View workflow job for this annotation

GitHub Actions / vale

[vale] cookbook/ru/README.md#L1

[Microsoft.Headings] 'Книга рецептов Yii3' should use sentence-style capitalization.
Raw output
{"message": "[Microsoft.Headings] 'Книга рецептов Yii3' should use sentence-style capitalization.", "location": {"path": "cookbook/ru/README.md", "range": {"start": {"line": 1, "column": 3}}}, "severity": "INFO"}

Книга рецептов Yii3 – это бесплатная книга, которая состоит из подсказок и секретов о PHP фреймворке [Yii3](https://www.yiiframework.com/).

Check failure on line 3 in cookbook/ru/README.md

View workflow job for this annotation

GitHub Actions / vale

[vale] cookbook/ru/README.md#L3

[Microsoft.Dashes] Remove the spaces around ' – '.
Raw output
{"message": "[Microsoft.Dashes] Remove the spaces around ' – '.", "location": {"path": "cookbook/ru/README.md", "range": {"start": {"line": 3, "column": 20}}}, "severity": "ERROR"}
Книга создана сообществом Yii. Поддерживается и редактируется силами команды Yii.

Не стесняйтесь создать pull request со своими рецептами. Мы сделаем ревью и добавим ваш рецепт в книгу.

Книга следует [правилам для документации Yii](https://www.yiiframework.com/doc/terms/).

---

[Вступление](preface.md)
[Интеграция с Sentry](sentry-integration.md)
31 changes: 31 additions & 0 deletions cookbook/ru/preface.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Вступление

Yii — высокопроизводительный компонентный PHP фреймворк для быстрой разработки современных веб-приложений.

Check failure on line 3 in cookbook/ru/preface.md

View workflow job for this annotation

GitHub Actions / vale

[vale] cookbook/ru/preface.md#L3

[Microsoft.Dashes] Remove the spaces around ' — '.
Raw output
{"message": "[Microsoft.Dashes] Remove the spaces around ' — '.", "location": {"path": "cookbook/ru/preface.md", "range": {"start": {"line": 3, "column": 4}}}, "severity": "ERROR"}
Имя Yii (произносится как `Yee` или `[ji:]`) означает "простой и эволюционирующий" по-китайски. Также оно может
расшифровываться как акроним **Yes It Is**!

Check failure on line 5 in cookbook/ru/preface.md

View workflow job for this annotation

GitHub Actions / vale

[vale] cookbook/ru/preface.md#L5

[Microsoft.Contractions] Use 'it's' instead of 'It Is'.
Raw output
{"message": "[Microsoft.Contractions] Use 'it's' instead of 'It Is'.", "location": {"path": "cookbook/ru/preface.md", "range": {"start": {"line": 5, "column": 36}}}, "severity": "ERROR"}

Yii является веб-фреймворком общего назначения. Он может использоваться для разработки любых типов приложений.
Благодаря компонентной архитектуре и хорошей поддержке кеширования, фреймворк отлично подходит для разработки
масштабных приложений, таких как порталы, форумы, CMS, магазины, REST API и так далее.

Check notice on line 9 in cookbook/ru/preface.md

View workflow job for this annotation

GitHub Actions / vale

[vale] cookbook/ru/preface.md#L9

[Microsoft.Acronyms] 'CMS' has no definition.
Raw output
{"message": "[Microsoft.Acronyms] 'CMS' has no definition.", "location": {"path": "cookbook/ru/preface.md", "range": {"start": {"line": 9, "column": 51}}}, "severity": "INFO"}

Check notice on line 9 in cookbook/ru/preface.md

View workflow job for this annotation

GitHub Actions / vale

[vale] cookbook/ru/preface.md#L9

[Microsoft.Acronyms] 'REST' has no definition.
Raw output
{"message": "[Microsoft.Acronyms] 'REST' has no definition.", "location": {"path": "cookbook/ru/preface.md", "range": {"start": {"line": 9, "column": 66}}}, "severity": "INFO"}

Полная документация и активное сообщество Yii позволяют значительно выиграть во времени разработки проектов
в долгосрочной перспективе.

## О чём эта книга?

Это книга для тех, кто уже знаком с Yii3, делает на нём проекты, прочитал основную документацию. Она затрагивает
фундаментально важные принципы разработки, подходы к архитектуре, интеграцию различных сервисов в Yii3 и так далее.

Книга состоит из отдельных рецептов, написанных экспертами по фреймворку. Рецепты объединены по теме, но вы можете
читать из в любом порядке так один не зависит от другого.


## Что понадобится перед чтением?

- Установленный Yii3.
- Вы должны быть уже знакомы с фреймворком и его документацией.

## Как помочь?

Если нашли описки, некорректную информацию, знаете как что-либо улучшить или же у вас есть новый рецепт для книги,
создайте issue или сделайте pull request [в репозиторий книги на GitHub](https://github.com/yiisoft/docs).
118 changes: 118 additions & 0 deletions cookbook/ru/sentry-integration.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
# Интеграция с Sentry

Check notice on line 1 in cookbook/ru/sentry-integration.md

View workflow job for this annotation

GitHub Actions / vale

[vale] cookbook/ru/sentry-integration.md#L1

[Microsoft.Headings] 'Интеграция с Sentry' should use sentence-style capitalization.
Raw output
{"message": "[Microsoft.Headings] 'Интеграция с Sentry' should use sentence-style capitalization.", "location": {"path": "cookbook/ru/sentry-integration.md", "range": {"start": {"line": 1, "column": 3}}}, "severity": "INFO"}

## Что такое Sentry

Check notice on line 3 in cookbook/ru/sentry-integration.md

View workflow job for this annotation

GitHub Actions / vale

[vale] cookbook/ru/sentry-integration.md#L3

[Microsoft.Headings] 'Что такое Sentry' should use sentence-style capitalization.
Raw output
{"message": "[Microsoft.Headings] 'Что такое Sentry' should use sentence-style capitalization.", "location": {"path": "cookbook/ru/sentry-integration.md", "range": {"start": {"line": 3, "column": 4}}}, "severity": "INFO"}

[Sentry](https://sentry.io/) – это инструмент мониторинга и отладки производительности и стабильности.

Check failure on line 5 in cookbook/ru/sentry-integration.md

View workflow job for this annotation

GitHub Actions / vale

[vale] cookbook/ru/sentry-integration.md#L5

[Microsoft.Dashes] Remove the spaces around ' – '.
Raw output
{"message": "[Microsoft.Dashes] Remove the spaces around ' – '.", "location": {"path": "cookbook/ru/sentry-integration.md", "range": {"start": {"line": 5, "column": 29}}}, "severity": "ERROR"}
Sentry представляет доступ к событиям, которые вы отправите туда из вашего приложения.

Чаще всего Sentry используется для мониторинга ошибок (исключений).
Ошибки можно "обогатить" контекстом для лучшего понимания вызванной проблемы:
- Аргументы, с которыми вызывалось приложение
- Теги, для группировки исключений
- Состояние среды окружения: переменные окружения, состояние приложения и прочие "глобальные" аттрибуты

Полный список всех возможностей можно найти на официальном сайте: https://sentry.io/welcome/

## Установка

### Установка пакета

Для установки нужного пакета установите пакет `yiisoft/yii-sentry` следующей командой:

```shell
composer require yiisoft/yii-sentry --prefer-dist

### Установка HTTP-драйвера

Библиотека [`getsentry/sentry-php`](https://github.com/getsentry/sentry-php) требует установки `php-http/httplug` пакета и любого HTTP-драйвера.
Для примеры используется адаптер `Guzzle`.

> Список всех адаптеров можно найти на [этой](https://docs.php-http.org/en/latest/clients.html#clients-adapters) странице.

Для установки пакетов выполните в консоли следующую команду.

```shell
composer require php-http/httplug php-http/guzzle7-adapter --prefer-dist

## Настройка

### Получение и сохранение токена

Далее сконфигурируем приложение.

Для начала зарегистрируйтесь в [Sentry](https://sentry.io) и создайте проект.

Далее в настройках проекта, на вкладке `General Settings`, найдите поле `Security Token` и скопируйте оттуда значение.

Теперь положите этот токен в настройки пакета. По умолчанию конфиг лежит в `config/packages/yiisoft/yii-sentry/config/params.php`.
Скопированный токен запишите в значение элемента массива по ключу `yiisoft/yii-sentry` => `options` => `dsn`. Пример:

```diff
'yiisoft/yii-sentry' => [
'enabled' => true,
'options' => [
- 'dsn' => '',
+ 'dsn' => 'ТОКЕН',
],
],
```


### Настройка HTTP-клиента

Check notice on line 61 in cookbook/ru/sentry-integration.md

View workflow job for this annotation

GitHub Actions / vale

[vale] cookbook/ru/sentry-integration.md#L61

[Microsoft.Headings] 'Настройка HTTP-клиента' should use sentence-style capitalization.
Raw output
{"message": "[Microsoft.Headings] 'Настройка HTTP-клиента' should use sentence-style capitalization.", "location": {"path": "cookbook/ru/sentry-integration.md", "range": {"start": {"line": 61, "column": 5}}}, "severity": "INFO"}

Check warning on line 61 in cookbook/ru/sentry-integration.md

View workflow job for this annotation

GitHub Actions / vale

[vale] cookbook/ru/sentry-integration.md#L61

[Microsoft.HeadingAcronyms] Avoid using acronyms in a title or heading.
Raw output
{"message": "[Microsoft.HeadingAcronyms] Avoid using acronyms in a title or heading.", "location": {"path": "cookbook/ru/sentry-integration.md", "range": {"start": {"line": 61, "column": 15}}}, "severity": "WARNING"}

После установки HTTP-клиента, сконфигурируйте его.

Создайте файл `config/common/sentry.php` и положите в него следующий код:

```php
<?php

declare(strict_types=1);

return [
\Http\Client\HttpClient::class => \GuzzleHttp\Client::class,
\Http\Client\HttpAsyncClient::class => [
'class' => \Http\Adapter\Guzzle7\Client::class,
'__construct()' => [
\Yiisoft\Factory\Definition\Reference::to(\Http\Client\HttpClient::class),
],
],
];
```

# Интеграция

### Веб

Поддержка Sentry для `web` реализована как `middleware`.

А это значит, что достаточно будет добавить `SentryMiddleware` в глобальный список `middleware` в `config/web/application.php`:


```diff
return [
Yiisoft\Yii\Web\Application::class => [
'__construct()' => [
'dispatcher' => DynamicReference::to(static function (Injector $injector) {
return ($injector->make(MiddlewareDispatcher::class))
->withMiddlewares(
[
Router::class,
SubFolder::class,
+ SentryMiddleware::class,
ErrorCatcher::class,
]
);
}),
'fallbackHandler' => Reference::to(NotFoundHandler::class),
],
],
];
```


### Консоль

Sentry поддерживает `console` в виде обработчика события [ConsoleEvents::ERROR](https://symfony.com/doc/current/components/console/events.html#the-consoleevents-error-event).

Check notice on line 116 in cookbook/ru/sentry-integration.md

View workflow job for this annotation

GitHub Actions / vale

[vale] cookbook/ru/sentry-integration.md#L116

[Microsoft.Acronyms] 'ERROR' has no definition.
Raw output
{"message": "[Microsoft.Acronyms] 'ERROR' has no definition.", "location": {"path": "cookbook/ru/sentry-integration.md", "range": {"start": {"line": 116, "column": 74}}}, "severity": "INFO"}

Пакет предоставляет конфигурационный файл, который автоматически подписывает приложение на это событие.
Loading