Skip to content

Commit f6ac3dc

Browse files
ArduanovDanilgithub-actions[bot]
authored andcommitted
Update translation
1 parent aaca7cb commit f6ac3dc

File tree

2 files changed

+494
-0
lines changed

2 files changed

+494
-0
lines changed

guide/ru/concept/configuration.md

Lines changed: 374 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,374 @@
1+
# Конфигурация
2+
3+
Существует множество способов настройки приложения. Мы сосредоточимся на
4+
концепциях, используемых в [шаблоне проекта по
5+
умолчанию](https://github.com/yiisoft/app).
6+
7+
Конфигурации Yii3 являются частью приложения. Вы можете изменить многие
8+
аспекты работы приложения, отредактировав конфигурацию в папке `config/`.
9+
10+
## Плагин конфигурации
11+
12+
В шаблоне приложения используется плагин
13+
[yiisoft/config](https://github.com/yiisoft/config). Поскольку написание
14+
всех конфигураций приложения с нуля - утомительный процесс, многие пакеты
15+
предлагают готовые конфигурации по умолчанию, а плагин помогает скопировать
16+
их в приложение.
17+
18+
Чтобы предлагать конфигурации по умолчанию, файл `composer.json` пакета
19+
должен содержать раздел `config-plugin`. При установке или обновлении
20+
пакетов с помощью Composer плагин считывает разделы `config-plugin` для
21+
каждой зависимости, копирует сами файлы в папку `config/packages/`
22+
приложения, если они ещё не существуют, и записывает план слияния в
23+
`config/packages/merge_plan.php`. План слияния определяет, как объединить
24+
конфигурации в один большой массив, готовый к передаче в [DI-контейнер]
25+
(di-container.md).
26+
27+
Посмотрите, что находится в `composer.json` "yiisoft/app" по умолчанию:
28+
29+
```json
30+
"config-plugin-options": {
31+
"output-directory": "config/packages"
32+
},
33+
"config-plugin": {
34+
"common": "config/common/*.php",
35+
"params": [
36+
"config/params.php",
37+
"?config/params-local.php"
38+
],
39+
"web": [
40+
"$common",
41+
"config/web/*.php"
42+
],
43+
"console": [
44+
"$common",
45+
"config/console/*.php"
46+
],
47+
"events": "config/events.php",
48+
"events-web": [
49+
"$events",
50+
"config/events-web.php"
51+
],
52+
"events-console": [
53+
"$events",
54+
"config/events-console.php"
55+
],
56+
"providers": "config/providers.php",
57+
"providers-web": [
58+
"$providers",
59+
"config/providers-web.php"
60+
],
61+
"providers-console": [
62+
"$providers",
63+
"config/providers-console.php"
64+
],
65+
"routes": "config/routes.php"
66+
},
67+
```
68+
69+
There are many named configs defined. For each name, there is a
70+
configuration.
71+
72+
A string means that the plugin takes config as is and merges it with
73+
same-named configs from packages you require. That happens if these
74+
packages have `config-plugin` in their `composer.json`.
75+
76+
The array means that the plugin will merge many files in the order they're
77+
specified.
78+
79+
`?` at the beginning of the file path indicated that the file may be
80+
absent. In this case, it's skipped.
81+
82+
`$` at the beginning of the name means a reference to another named config.
83+
84+
`params` is a bit special because it's reserved for application
85+
parameters. These are automatically available as `$params` in all other
86+
configuration files.
87+
88+
You can learn more about config plugin features [from its
89+
documentation](https://github.com/yiisoft/config/blob/master/README.md).
90+
91+
## Config files
92+
93+
Now, as you know how the plugin assembles configs, look at `config`
94+
directory:
95+
96+
```
97+
common/
98+
application-parameters.php
99+
i18n.php
100+
router.php
101+
console/
102+
packages/
103+
yiisoft/
104+
dist.lock
105+
merge_plan.php
106+
web/
107+
application.php
108+
psr17.php
109+
events.php
110+
events-console.php
111+
events-web.php
112+
params.php
113+
providers.php
114+
providers-console.php
115+
providers-web.php
116+
routes.php
117+
```
118+
119+
### Конфигурация контейнера
120+
121+
The application consists of a set of services registered in a [dependency
122+
container](di-container.md). The config files that responsible for direct
123+
dependency container configuration are under `common/`, `console/` and
124+
`web/` directories. We use `web/` for config specific to web application
125+
and `console/` for config specific to console commands. Both web and console
126+
are sharing configuration under `common/`.
127+
128+
```php
129+
<?php
130+
131+
declare(strict_types=1);
132+
133+
use App\ApplicationParameters;
134+
135+
/** @var array $params */
136+
137+
return [
138+
ApplicationParameters::class => [
139+
'class' => ApplicationParameters::class,
140+
'charset()' => [$params['app']['charset']],
141+
'name()' => [$params['app']['name']],
142+
],
143+
];
144+
```
145+
146+
Config plugin passes special `$params` variable to all config files. The
147+
code passes its values to the service.
148+
149+
The guide on ["Dependency injection and container"](di-container.md)
150+
describes the configuration format and the idea of dependency injection in
151+
detail.
152+
153+
For convenience, there is a naming convention for custom string keys:
154+
155+
1. Prefix package name such as `yiisoft/cache-file/custom-definition`.
156+
2. In case configuration are for the application itself, skip package
157+
prefix, such as `custom-definition`.
158+
159+
### Service providers
160+
161+
As an alternative to registering dependencies directly, you can use service
162+
providers. Basically, these are classes that given parameters are
163+
configuring and registering services within the container. Similar to three
164+
dependency configuration files described, there are three configs for
165+
specifying service providers: `providers-console.php` for console commands,
166+
`providers-web.php` for web application and `providers.php` for both:
167+
168+
```php
169+
/* @var array $params */
170+
171+
// ...
172+
use App\Provider\CacheProvider;
173+
use App\Provider\MiddlewareProvider;
174+
// ...
175+
176+
return [
177+
// ...
178+
'yiisoft/yii-web/middleware' => MiddlewareProvider::class,
179+
'yiisoft/cache/cache' => [
180+
'class' => CacheProvider::class,
181+
'__construct()' => [
182+
$params['yiisoft/cache-file']['file-cache']['path'],
183+
],
184+
],
185+
// ...
186+
```
187+
188+
In this config keys are provider names. By convention these are
189+
`vendor/package-name/provider-name`. Values are provider class names. These
190+
classes could be either created in the project itself or provided by a
191+
package.
192+
193+
If you need to configure some options for a service, similar to direct
194+
container configuration, take values from `$params` and pass them to
195+
providers.
196+
197+
Provider should implement a single method, `public function
198+
register(Container $container): void`. In this method you need to add a
199+
service to container using `set()` method. Below is a provider for a cache
200+
service:
201+
202+
```php
203+
use Psr\Container\ContainerInterface;
204+
use Psr\SimpleCache\CacheInterface;
205+
use Yiisoft\Aliases\Aliases;
206+
use Yiisoft\Cache\Cache;
207+
use Yiisoft\Cache\CacheInterface as YiiCacheInterface;
208+
use Yiisoft\Cache\File\FileCache;
209+
use Yiisoft\Di\Container;
210+
use Yiisoft\Di\Support\ServiceProvider;
211+
212+
final readonly class CacheProvider extends ServiceProvider
213+
{
214+
public function __construct(
215+
private string $cachePath = '@runtime/cache'
216+
)
217+
{
218+
$this->cachePath = $cachePath;
219+
}
220+
221+
public function register(Container $container): void
222+
{
223+
$container->set(CacheInterface::class, function (ContainerInterface $container) {
224+
$aliases = $container->get(Aliases::class);
225+
226+
return new FileCache($aliases->get($this->cachePath));
227+
});
228+
229+
$container->set(YiiCacheInterface::class, Cache::class);
230+
}
231+
}
232+
```
233+
234+
### Routes
235+
236+
You can configure how web application responds to certain URLs in
237+
`config/routes.php`:
238+
239+
```php
240+
use App\Controller\SiteController;
241+
use Yiisoft\Router\Route;
242+
243+
return [
244+
Route::get('/')->action([SiteController::class, 'index'])->name('site/index')
245+
];
246+
```
247+
248+
Read more about it in ["Routes"](../runtime/routing.md).
249+
250+
### Events
251+
252+
Many services emit certain events that you can attach to. You could do that
253+
via three config files: `events-web.php` for web application events,
254+
`events-console.php` for console events and `events.php` for both. The
255+
configuration is an array where keys are event names and values are an array
256+
of handlers:
257+
258+
```php
259+
return [
260+
EventName::class => [
261+
// Just a regular closure, it will be called from the Dispatcher "as is".
262+
static fn (EventName $event) => someStuff($event),
263+
264+
// A regular closure with an extra dependency. All the parameters after the first one (the event itself)
265+
// will be resolved from your DI container within `yiisoft/injector`.
266+
static fn (EventName $event, DependencyClass $dependency) => someStuff($event),
267+
268+
// An example with a regular callable. If the `staticMethodName` method has some dependencies,
269+
// they will be resolved the same way as in the earlier example.
270+
[SomeClass::class, 'staticMethodName'],
271+
272+
// Non-static methods are allowed too. In this case, `SomeClass` will be instantiated by your DI container.
273+
[SomeClass::class, 'methodName'],
274+
275+
// An object of a class with the `__invoke` method implemented
276+
new InvokableClass(),
277+
278+
// In this case, the `InvokableClass` with the `__invoke` method will be instantiated by your DI container
279+
InvokableClass::class,
280+
281+
// Any definition of an invokable class may be here while your `$container->has('the definition)`
282+
'di-alias'
283+
],
284+
];
285+
```
286+
287+
Read more about it in ["Events"](events.md).
288+
289+
290+
### Parameters
291+
292+
Parameters, `config/params.php` store configuration values that are used in
293+
other config files to configuring services and service providers.
294+
295+
> [!TIP]
296+
> Don't use parameters, constants or environment variables directly in your application, configure
297+
> services instead.
298+
299+
Default application `params.php` looks like the following:
300+
301+
```php
302+
<?php
303+
304+
declare(strict_types=1);
305+
306+
use App\Command\Hello;
307+
use App\ViewInjection\ContentViewInjection;
308+
use App\ViewInjection\LayoutViewInjection;
309+
use Yiisoft\Definitions\Reference;
310+
use Yiisoft\Yii\View\CsrfViewInjection;
311+
312+
return [
313+
'app' => [
314+
'charset' => 'UTF-8',
315+
'locale' => 'en',
316+
'name' => 'My Project',
317+
],
318+
319+
'yiisoft/aliases' => [
320+
'aliases' => [
321+
'@root' => dirname(__DIR__),
322+
'@assets' => '@root/public/assets',
323+
'@assetsUrl' => '/assets',
324+
'@baseUrl' => '/',
325+
'@message' => '@root/resources/message',
326+
'@npm' => '@root/node_modules',
327+
'@public' => '@root/public',
328+
'@resources' => '@root/resources',
329+
'@runtime' => '@root/runtime',
330+
'@vendor' => '@root/vendor',
331+
'@layout' => '@resources/views/layout',
332+
'@views' => '@resources/views',
333+
],
334+
],
335+
336+
'yiisoft/yii-view' => [
337+
'injections' => [
338+
Reference::to(ContentViewInjection::class),
339+
Reference::to(CsrfViewInjection::class),
340+
Reference::to(LayoutViewInjection::class),
341+
],
342+
],
343+
344+
'yiisoft/yii-console' => [
345+
'commands' => [
346+
'hello' => Hello::class,
347+
],
348+
],
349+
];
350+
```
351+
352+
For convenience, there is a naming convention about parameters:
353+
354+
1. Group parameters package name such as `yiisoft/cache-file`.
355+
2. In case parameters are for the application itself, as in `app`, skip
356+
package prefix.
357+
3. In case there are many services in the package, such as `file-target` and
358+
`file-rotator` in `yiisoft/log-target-file` package, group parameters by
359+
service name.
360+
4. Use `enabled` as parameter name to be able to disable or enable a
361+
service, such as `yiisoft/yii-debug`.
362+
363+
### Package configs
364+
365+
Config plugin described copy default package configurations to `packages/`
366+
directory. Once copied you own the configs, so you can adjust these as you
367+
like. `yiisoft/` in the default template stands for package vendor. Since
368+
only `yiisoft` packages are in template, there's a single
369+
directory. `merge_plan.php` is used in runtime to get the order on how
370+
configs are merged. Note that for config keys there should be a single
371+
source of truth. One config can't override values of another config.
372+
373+
`dist.lock` is used by the plugin to keep track of changes and display diff
374+
between current config and example one.

0 commit comments

Comments
 (0)