diff --git a/_translations/guide/po/ru/concept_configuration.md.po b/_translations/guide/po/ru/concept_configuration.md.po index 66298e24..453f5636 100644 --- a/_translations/guide/po/ru/concept_configuration.md.po +++ b/_translations/guide/po/ru/concept_configuration.md.po @@ -5,9 +5,9 @@ # msgid "" msgstr "" -"Project-Id-Version: PACKAGE VERSION\n" +"Project-Id-Version: \n" "POT-Creation-Date: 2025-09-04 11:19+0500\n" -"PO-Revision-Date: 2025-09-04 11:19+0500\n" +"PO-Revision-Date: 2025-10-01 13:33+0500\n" "Last-Translator: Automatically generated\n" "Language-Team: none\n" "Language: ru\n" @@ -15,44 +15,45 @@ msgstr "" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n" +"X-Generator: Poedit 3.7\n" #. type: Title ## #: en/concept/configuration.md en/tutorial/using-yii-with-roadrunner.md #: en/views/view-injections.md -#, fuzzy, no-wrap +#, no-wrap msgid "Configuration" -msgstr "конфигурация может быть:" +msgstr "Конфигурация" #. type: Plain text #: en/concept/configuration.md msgid "There are many ways to configure your application. We will focus on concepts used in the [default project template](https://github.com/yiisoft/app)." -msgstr "" +msgstr "Существует множество способов настройки приложения. Мы сосредоточимся на концепциях, используемых в [шаблоне проекта по умолчанию](https://github.com/yiisoft/app)." #. type: Plain text #: en/concept/configuration.md msgid "Yii3 configs are part of the application. You can change many aspects of how the application works by editing configuration under `config/`." -msgstr "" +msgstr "Конфигурации Yii3 являются частью приложения. Вы можете изменить многие аспекты работы приложения, отредактировав конфигурацию в папке `config/`." #. type: Title ## #: en/concept/configuration.md #, no-wrap msgid "Config plugin" -msgstr "" +msgstr "Плагин конфигурации" #. type: Plain text #: en/concept/configuration.md msgid "In the application template [yiisoft/config](https://github.com/yiisoft/config) is used. Since writing all application configurations from scratch is a tedious process, many packages offer default configs, and the plugin helps with copying these into the application." -msgstr "" +msgstr "В шаблоне приложения используется плагин [yiisoft/config](https://github.com/yiisoft/config). Поскольку написание всех конфигураций приложения с нуля - утомительный процесс, многие пакеты предлагают готовые конфигурации по умолчанию, а плагин помогает скопировать их в приложение." #. type: Plain text #: en/concept/configuration.md msgid "To offer default configs, `composer.json` of the package has to have `config-plugin` section. When installing or updating packages with Composer, the plugin reads `config-plugin` sections for each dependency, copies files themselves to application `config/packages/` if they don't yet exist and writes a merge plan to `config/packages/merge_plan.php`. The merge plan defines how to merge the configs into a single big array ready to be passed to [DI container](di-container.md)." -msgstr "" +msgstr "Чтобы предлагать конфигурации по умолчанию, файл `composer.json` пакета должен содержать раздел `config-plugin`. При установке или обновлении пакетов с помощью Composer плагин считывает разделы `config-plugin` для каждой зависимости, копирует сами файлы в папку `config/packages/` приложения, если они ещё не существуют, и записывает план слияния в `config/packages/merge_plan.php`. План слияния определяет, как объединить конфигурации в один большой массив, готовый к передаче в [DI-контейнер] (di-container.md)." #. type: Plain text #: en/concept/configuration.md msgid "Take a look at what's in the \"yiisoft/app\" `composer.json` by default:" -msgstr "" +msgstr "Посмотрите, что находится в `composer.json` \"yiisoft/app\" по умолчанию:" #. type: Fenced code block (json) #: en/concept/configuration.md @@ -96,6 +97,43 @@ msgid "" " \"routes\": \"config/routes.php\"\n" "},\n" msgstr "" +"\"config-plugin-options\": {\n" +" \"output-directory\": \"config/packages\"\n" +"},\n" +"\"config-plugin\": {\n" +" \"common\": \"config/common/*.php\",\n" +" \"params\": [\n" +" \"config/params.php\",\n" +" \"?config/params-local.php\"\n" +" ],\n" +" \"web\": [\n" +" \"$common\",\n" +" \"config/web/*.php\"\n" +" ],\n" +" \"console\": [\n" +" \"$common\",\n" +" \"config/console/*.php\"\n" +" ],\n" +" \"events\": \"config/events.php\",\n" +" \"events-web\": [\n" +" \"$events\",\n" +" \"config/events-web.php\"\n" +" ],\n" +" \"events-console\": [\n" +" \"$events\",\n" +" \"config/events-console.php\"\n" +" ],\n" +" \"providers\": \"config/providers.php\",\n" +" \"providers-web\": [\n" +" \"$providers\",\n" +" \"config/providers-web.php\"\n" +" ],\n" +" \"providers-console\": [\n" +" \"$providers\",\n" +" \"config/providers-console.php\"\n" +" ],\n" +" \"routes\": \"config/routes.php\"\n" +"},\n" #. type: Plain text #: en/concept/configuration.md @@ -171,10 +209,9 @@ msgstr "" #. type: Title ### #: en/concept/configuration.md -#, fuzzy, no-wrap -#| msgid "Secure server configuration" +#, no-wrap msgid "Container configuration" -msgstr "Безопасная конфигурация сервера" +msgstr "Конфигурация контейнера" #. type: Plain text #: en/concept/configuration.md diff --git a/_translations/guide/po/ru/tutorial_using-yii-with-roadrunner.md.po b/_translations/guide/po/ru/tutorial_using-yii-with-roadrunner.md.po index 3003d389..0a639a2f 100644 --- a/_translations/guide/po/ru/tutorial_using-yii-with-roadrunner.md.po +++ b/_translations/guide/po/ru/tutorial_using-yii-with-roadrunner.md.po @@ -19,9 +19,9 @@ msgstr "" #. type: Title ## #: en/concept/configuration.md en/tutorial/using-yii-with-roadrunner.md #: en/views/view-injections.md -#, fuzzy, no-wrap +#, no-wrap msgid "Configuration" -msgstr "конфигурация может быть:" +msgstr "Конфигурация" #. type: Title # #: en/tutorial/using-yii-with-roadrunner.md diff --git a/_translations/guide/po/ru/views_view-injections.md.po b/_translations/guide/po/ru/views_view-injections.md.po index 0260c7b7..9123a5bd 100644 --- a/_translations/guide/po/ru/views_view-injections.md.po +++ b/_translations/guide/po/ru/views_view-injections.md.po @@ -20,9 +20,9 @@ msgstr "" #: ../../guide/en/concept/configuration.md #: ../../guide/en/tutorial/using-yii-with-roadrunner.md #: ../../guide/en/views/view-injections.md -#, fuzzy, no-wrap +#, no-wrap msgid "Configuration" -msgstr "конфигурация может быть:" +msgstr "Конфигурация" #. type: Title # #: ../../guide/en/views/view-injections.md diff --git a/guide/ru/concept/configuration.md b/guide/ru/concept/configuration.md new file mode 100644 index 00000000..91cbb420 --- /dev/null +++ b/guide/ru/concept/configuration.md @@ -0,0 +1,374 @@ +# Конфигурация + +Существует множество способов настройки приложения. Мы сосредоточимся на +концепциях, используемых в [шаблоне проекта по +умолчанию](https://github.com/yiisoft/app). + +Конфигурации Yii3 являются частью приложения. Вы можете изменить многие +аспекты работы приложения, отредактировав конфигурацию в папке `config/`. + +## Плагин конфигурации + +В шаблоне приложения используется плагин +[yiisoft/config](https://github.com/yiisoft/config). Поскольку написание +всех конфигураций приложения с нуля - утомительный процесс, многие пакеты +предлагают готовые конфигурации по умолчанию, а плагин помогает скопировать +их в приложение. + +Чтобы предлагать конфигурации по умолчанию, файл `composer.json` пакета +должен содержать раздел `config-plugin`. При установке или обновлении +пакетов с помощью Composer плагин считывает разделы `config-plugin` для +каждой зависимости, копирует сами файлы в папку `config/packages/` +приложения, если они ещё не существуют, и записывает план слияния в +`config/packages/merge_plan.php`. План слияния определяет, как объединить +конфигурации в один большой массив, готовый к передаче в [DI-контейнер] +(di-container.md). + +Посмотрите, что находится в `composer.json` "yiisoft/app" по умолчанию: + +```json +"config-plugin-options": { + "output-directory": "config/packages" +}, +"config-plugin": { + "common": "config/common/*.php", + "params": [ + "config/params.php", + "?config/params-local.php" + ], + "web": [ + "$common", + "config/web/*.php" + ], + "console": [ + "$common", + "config/console/*.php" + ], + "events": "config/events.php", + "events-web": [ + "$events", + "config/events-web.php" + ], + "events-console": [ + "$events", + "config/events-console.php" + ], + "providers": "config/providers.php", + "providers-web": [ + "$providers", + "config/providers-web.php" + ], + "providers-console": [ + "$providers", + "config/providers-console.php" + ], + "routes": "config/routes.php" +}, +``` + +There are many named configs defined. For each name, there is a +configuration. + +A string means that the plugin takes config as is and merges it with +same-named configs from packages you require. That happens if these +packages have `config-plugin` in their `composer.json`. + +The array means that the plugin will merge many files in the order they're +specified. + +`?` at the beginning of the file path indicated that the file may be +absent. In this case, it's skipped. + +`$` at the beginning of the name means a reference to another named config. + +`params` is a bit special because it's reserved for application +parameters. These are automatically available as `$params` in all other +configuration files. + +You can learn more about config plugin features [from its +documentation](https://github.com/yiisoft/config/blob/master/README.md). + +## Config files + +Now, as you know how the plugin assembles configs, look at `config` +directory: + +``` +common/ + application-parameters.php + i18n.php + router.php +console/ +packages/ + yiisoft/ + dist.lock + merge_plan.php +web/ + application.php + psr17.php +events.php +events-console.php +events-web.php +params.php +providers.php +providers-console.php +providers-web.php +routes.php +``` + +### Конфигурация контейнера + +The application consists of a set of services registered in a [dependency +container](di-container.md). The config files that responsible for direct +dependency container configuration are under `common/`, `console/` and +`web/` directories. We use `web/` for config specific to web application +and `console/` for config specific to console commands. Both web and console +are sharing configuration under `common/`. + +```php + [ + 'class' => ApplicationParameters::class, + 'charset()' => [$params['app']['charset']], + 'name()' => [$params['app']['name']], + ], +]; +``` + +Config plugin passes special `$params` variable to all config files. The +code passes its values to the service. + +The guide on ["Dependency injection and container"](di-container.md) +describes the configuration format and the idea of dependency injection in +detail. + +For convenience, there is a naming convention for custom string keys: + +1. Prefix package name such as `yiisoft/cache-file/custom-definition`. +2. In case configuration are for the application itself, skip package + prefix, such as `custom-definition`. + +### Service providers + +As an alternative to registering dependencies directly, you can use service +providers. Basically, these are classes that given parameters are +configuring and registering services within the container. Similar to three +dependency configuration files described, there are three configs for +specifying service providers: `providers-console.php` for console commands, +`providers-web.php` for web application and `providers.php` for both: + +```php +/* @var array $params */ + +// ... +use App\Provider\CacheProvider; +use App\Provider\MiddlewareProvider; +// ... + +return [ + // ... + 'yiisoft/yii-web/middleware' => MiddlewareProvider::class, + 'yiisoft/cache/cache' => [ + 'class' => CacheProvider::class, + '__construct()' => [ + $params['yiisoft/cache-file']['file-cache']['path'], + ], + ], + // ... +``` + +In this config keys are provider names. By convention these are +`vendor/package-name/provider-name`. Values are provider class names. These +classes could be either created in the project itself or provided by a +package. + +If you need to configure some options for a service, similar to direct +container configuration, take values from `$params` and pass them to +providers. + +Provider should implement a single method, `public function +register(Container $container): void`. In this method you need to add a +service to container using `set()` method. Below is a provider for a cache +service: + +```php +use Psr\Container\ContainerInterface; +use Psr\SimpleCache\CacheInterface; +use Yiisoft\Aliases\Aliases; +use Yiisoft\Cache\Cache; +use Yiisoft\Cache\CacheInterface as YiiCacheInterface; +use Yiisoft\Cache\File\FileCache; +use Yiisoft\Di\Container; +use Yiisoft\Di\Support\ServiceProvider; + +final readonly class CacheProvider extends ServiceProvider +{ + public function __construct( + private string $cachePath = '@runtime/cache' + ) + { + $this->cachePath = $cachePath; + } + + public function register(Container $container): void + { + $container->set(CacheInterface::class, function (ContainerInterface $container) { + $aliases = $container->get(Aliases::class); + + return new FileCache($aliases->get($this->cachePath)); + }); + + $container->set(YiiCacheInterface::class, Cache::class); + } +} +``` + +### Routes + +You can configure how web application responds to certain URLs in +`config/routes.php`: + +```php +use App\Controller\SiteController; +use Yiisoft\Router\Route; + +return [ + Route::get('/')->action([SiteController::class, 'index'])->name('site/index') +]; +``` + +Read more about it in ["Routes"](../runtime/routing.md). + +### Events + +Many services emit certain events that you can attach to. You could do that +via three config files: `events-web.php` for web application events, +`events-console.php` for console events and `events.php` for both. The +configuration is an array where keys are event names and values are an array +of handlers: + +```php +return [ + EventName::class => [ + // Just a regular closure, it will be called from the Dispatcher "as is". + static fn (EventName $event) => someStuff($event), + + // A regular closure with an extra dependency. All the parameters after the first one (the event itself) + // will be resolved from your DI container within `yiisoft/injector`. + static fn (EventName $event, DependencyClass $dependency) => someStuff($event), + + // An example with a regular callable. If the `staticMethodName` method has some dependencies, + // they will be resolved the same way as in the earlier example. + [SomeClass::class, 'staticMethodName'], + + // Non-static methods are allowed too. In this case, `SomeClass` will be instantiated by your DI container. + [SomeClass::class, 'methodName'], + + // An object of a class with the `__invoke` method implemented + new InvokableClass(), + + // In this case, the `InvokableClass` with the `__invoke` method will be instantiated by your DI container + InvokableClass::class, + + // Any definition of an invokable class may be here while your `$container->has('the definition)` + 'di-alias' + ], +]; +``` + +Read more about it in ["Events"](events.md). + + +### Parameters + +Parameters, `config/params.php` store configuration values that are used in +other config files to configuring services and service providers. + +> [!TIP] +> Don't use parameters, constants or environment variables directly in your application, configure +> services instead. + +Default application `params.php` looks like the following: + +```php + [ + 'charset' => 'UTF-8', + 'locale' => 'en', + 'name' => 'My Project', + ], + + 'yiisoft/aliases' => [ + 'aliases' => [ + '@root' => dirname(__DIR__), + '@assets' => '@root/public/assets', + '@assetsUrl' => '/assets', + '@baseUrl' => '/', + '@message' => '@root/resources/message', + '@npm' => '@root/node_modules', + '@public' => '@root/public', + '@resources' => '@root/resources', + '@runtime' => '@root/runtime', + '@vendor' => '@root/vendor', + '@layout' => '@resources/views/layout', + '@views' => '@resources/views', + ], + ], + + 'yiisoft/yii-view' => [ + 'injections' => [ + Reference::to(ContentViewInjection::class), + Reference::to(CsrfViewInjection::class), + Reference::to(LayoutViewInjection::class), + ], + ], + + 'yiisoft/yii-console' => [ + 'commands' => [ + 'hello' => Hello::class, + ], + ], +]; +``` + +For convenience, there is a naming convention about parameters: + +1. Group parameters package name such as `yiisoft/cache-file`. +2. In case parameters are for the application itself, as in `app`, skip + package prefix. +3. In case there are many services in the package, such as `file-target` and + `file-rotator` in `yiisoft/log-target-file` package, group parameters by + service name. +4. Use `enabled` as parameter name to be able to disable or enable a + service, such as `yiisoft/yii-debug`. + +### Package configs + +Config plugin described copy default package configurations to `packages/` +directory. Once copied you own the configs, so you can adjust these as you +like. `yiisoft/` in the default template stands for package vendor. Since +only `yiisoft` packages are in template, there's a single +directory. `merge_plan.php` is used in runtime to get the order on how +configs are merged. Note that for config keys there should be a single +source of truth. One config can't override values of another config. + +`dist.lock` is used by the plugin to keep track of changes and display diff +between current config and example one. diff --git a/guide/ru/views/view-injections.md b/guide/ru/views/view-injections.md new file mode 100644 index 00000000..05b19fce --- /dev/null +++ b/guide/ru/views/view-injections.md @@ -0,0 +1,120 @@ +# View injections + +The view injections are designed to provide a standardized way to pass +parameters to the common layer of views in an application. It allows +developers to manage the data that will be available across various views, +ensuring flexibility and reusability of code. + +The view injections could be used if you require `yiisoft/yii-view-renderer` +package: + + +```sh +composer require yiisoft/yii-view-renderer +``` + +## Конфигурация + +In config `params.php`: + + +```php +... +'yiisoft/yii-view' => [ + 'injections' => [ + Reference::to(ContentViewInjection::class), + Reference::to(CsrfViewInjection::class), + Reference::to(LayoutViewInjection::class), + ], + ], +``` + +## New injections + +Start by defining a class that will implement the +`Yiisoft\Yii\View\Renderer\CommonParametersInjectionInterface`. This class +will be responsible for providing the parameters you want to inject into +your view templates and layouts. + +```php +class MyCustomParametersInjection implements Yiisoft\Yii\View\Renderer\CommonParametersInjectionInterface +{ + // Class properties and methods will go here + + public function __construct(UserService $userService) + { + $this->userService = $userService; + } + + public function getCommonParameters(): array + { + return [ + 'siteName' => 'My Awesome Site', + 'currentYear' => date('Y'), + 'user' => $this->userService->getCurrentUser(), + ]; + } +} +``` + +Add your new Injection to `params.php`: + +```php +'yiisoft/yii-view' => [ + 'injections' => [ + ..., + Reference::to(MyCustomParametersInjection::class), + ], + ], +``` + +## Using Separate Injections for Different Layouts + +If your application has multiple layouts, you can create separate parameter +injections for each layout. This approach allows you to tailor the +parameters injected into each layout according to its specific needs, +enhancing the flexibility and maintainability of your application. + +Create your custom ViewInjection for a specific layout: + +```php +readonly final class CartViewInjection implements CommonParametersInjectionInterface +{ + public function __construct(private Cart $cart) + { + } + + public function getCommonParameters(): array + { + return [ + 'cart' => $this->cart, + ]; + } +} +``` + +Add your new injection to `params.php` under specific layout name. In the +following example, it is `@layout/cart`: + +```php +'yiisoft/yii-view' => [ + 'injections' => [ + ..., + Reference::to(MyCustomParametersInjection::class), + DynamicReference::to(static function (ContainerInterface $container) { + $cart = $container + ->get(Cart::class); + + return new LayoutSpecificInjections( + '@layout/cart', // layout name for injection + + new CartViewInjection($cart) + ); + }), + ], + ], +``` + +> [!NOTE] +> [← Template engines](template-engines.md) | +> [Scripts, styles and metatags →](script-style-meta.md)