diff --git a/cookbook/en/README.md b/cookbook/en/README.md index 7d4ad10e..6e50ac36 100644 --- a/cookbook/en/README.md +++ b/cookbook/en/README.md @@ -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) diff --git a/cookbook/en/preface.md b/cookbook/en/preface.md index 8708fce2..bf62ceb8 100644 --- a/cookbook/en/preface.md +++ b/cookbook/en/preface.md @@ -11,7 +11,7 @@ it's especially suitable for developing large-scale applications such as portals e-commerce, REST APIs, etc. 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 @@ -24,7 +24,7 @@ These go by topic, but you are free to read them in any order as there is no dep ## 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 diff --git a/cookbook/en/sentry-integration.md b/cookbook/en/sentry-integration.md new file mode 100644 index 00000000..4098ddc8 --- /dev/null +++ b/cookbook/en/sentry-integration.md @@ -0,0 +1,117 @@ +# Sentry integration + +## What is Sentry + +[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). +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 + +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. + +> 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`. +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 + +After installing the HTTP client, configure it. + +Create the file `config/common/sentry.php` and put the following code into it: + +```php + \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. + +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. + +The package provides a configuration file that automatically subscribes the application to this event. diff --git a/cookbook/ru/README.md b/cookbook/ru/README.md new file mode 100644 index 00000000..1a24a7de --- /dev/null +++ b/cookbook/ru/README.md @@ -0,0 +1,13 @@ +# Книга рецептов Yii3 + +Книга рецептов Yii3 – это бесплатная книга, которая состоит из подсказок и секретов о PHP фреймворке [Yii3](https://www.yiiframework.com/). +Книга создана сообществом Yii. Поддерживается и редактируется силами команды Yii. + +Не стесняйтесь создать pull request со своими рецептами. Мы сделаем ревью и добавим ваш рецепт в книгу. + +Книга следует [правилам для документации Yii](https://www.yiiframework.com/doc/terms/). + +--- + +[Вступление](preface.md) +[Интеграция с Sentry](sentry-integration.md) diff --git a/cookbook/ru/preface.md b/cookbook/ru/preface.md new file mode 100644 index 00000000..fcd18517 --- /dev/null +++ b/cookbook/ru/preface.md @@ -0,0 +1,31 @@ +# Вступление + +Yii — высокопроизводительный компонентный PHP фреймворк для быстрой разработки современных веб-приложений. +Имя Yii (произносится как `Yee` или `[ji:]`) означает "простой и эволюционирующий" по-китайски. Также оно может +расшифровываться как акроним **Yes It Is**! + +Yii является веб-фреймворком общего назначения. Он может использоваться для разработки любых типов приложений. +Благодаря компонентной архитектуре и хорошей поддержке кеширования, фреймворк отлично подходит для разработки +масштабных приложений, таких как порталы, форумы, CMS, магазины, REST API и так далее. + +Полная документация и активное сообщество Yii позволяют значительно выиграть во времени разработки проектов +в долгосрочной перспективе. + +## О чём эта книга? + +Это книга для тех, кто уже знаком с Yii3, делает на нём проекты, прочитал основную документацию. Она затрагивает +фундаментально важные принципы разработки, подходы к архитектуре, интеграцию различных сервисов в Yii3 и так далее. + +Книга состоит из отдельных рецептов, написанных экспертами по фреймворку. Рецепты объединены по теме, но вы можете +читать из в любом порядке так один не зависит от другого. + + +## Что понадобится перед чтением? + +- Установленный Yii3. +- Вы должны быть уже знакомы с фреймворком и его документацией. + +## Как помочь? + +Если нашли описки, некорректную информацию, знаете как что-либо улучшить или же у вас есть новый рецепт для книги, +создайте issue или сделайте pull request [в репозиторий книги на GitHub](https://github.com/yiisoft/docs). diff --git a/cookbook/ru/sentry-integration.md b/cookbook/ru/sentry-integration.md new file mode 100644 index 00000000..4c8f5442 --- /dev/null +++ b/cookbook/ru/sentry-integration.md @@ -0,0 +1,118 @@ +# Интеграция с Sentry + +## Что такое Sentry + +[Sentry](https://sentry.io/) – это инструмент мониторинга и отладки производительности и стабильности. +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-клиента + +После установки HTTP-клиента, сконфигурируйте его. + +Создайте файл `config/common/sentry.php` и положите в него следующий код: + +```php + \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). + +Пакет предоставляет конфигурационный файл, который автоматически подписывает приложение на это событие.