Yii DI

Общие вопросы по использованию второй версии фреймворка. Если не знаете как что-то сделать и это про Yii 2, вам сюда.
Ответить
german.igortcev
Сообщения: 251
Зарегистрирован: 2014.08.18, 14:01

Yii DI

Сообщение german.igortcev »

Добрый день, Дайте совет как Redis подгрузить через DI и уйти от кода ниже в конструкторе, к примеру добавив в конфиг

Код: Выделить всё

	'components' => [
		'googleSearchConsoleLimiter' => [
                'class' => \backend\modules\integration\googleSearchConsole\components\GoogleSearchConsoleLimiter::class,
                'requestsAllowedPerSecond' => 50,
                'requestsAllowedPerMinute' => 120,
                'requestsAllowedPerDay' => 100000000,
                'storageKeyPerSecond' => 'executed_per_second',
                'storageKeyPerMinute' => 'executed_per_minute',
               'storageKeyPerDay' => 'executed_per_day',
            ],
        ]
        
        
        'components' => [
		'googleSearchConsoleLimiter' => [
                'class' => \backend\modules\integration\googleSearchConsole\components\GoogleSearchConsoleLimiter::class,
                'storage' => [
                	'class' => SomeStorageClass
                ],
                'requestsAllowedPerSecond' => 50,
                'requestsAllowedPerMinute' => 120,
                'requestsAllowedPerDay' => 100000000,
                'storageKeyPerSecond' => 'executed_per_second',
                'storageKeyPerMinute' => 'executed_per_minute',
                storageKeyPerDay' => 'executed_per_day',
            ],
        ]

Код: Выделить всё


    public function __construct($config = [])
    {
        $this->storage = \Yii::$app->get('redis');

        parent::__construct($config);
    }
Аватара пользователя
samdark
Администратор
Сообщения: 9489
Зарегистрирован: 2009.04.02, 13:46
Откуда: Воронеж
Контактная информация:

Re: Yii DI

Сообщение samdark »

Нужно использовать последнюю версию Yii. Допустим, есть два компонента-сервиса:

Код: Выделить всё

<?php


namespace app\components;


use yii\base\Component;

class TestComponent extends Component
{
    private DependencyComponent $dependency;

    public function __construct(DependencyComponent $dependency)
    {
        $this->dependency = $dependency;
    }

    public function test()
    {
        echo $this->dependency->doit();
    }
}
и

Код: Выделить всё

<?php


namespace app\components;


use yii\base\Component;

class DependencyComponent extends Component
{
    public function doit()
    {
        return 'test';
    }
}
В конфиге в 'components' прописываем так:

Код: Выделить всё

'testComponent' => [
    'class' => \app\components\TestComponent::class,
],
В контроллере:

Код: Выделить всё

public function actionTest(\app\components\TestComponent $testComponent)
{
    $testComponent->test();
}
german.igortcev
Сообщения: 251
Зарегистрирован: 2014.08.18, 14:01

Re: Yii DI

Сообщение german.igortcev »

samdark писал(а): 2021.05.27, 10:19 Нужно использовать последнюю версию Yii. Допустим, есть два компонента-сервиса:

Код: Выделить всё

<?php


namespace app\components;


use yii\base\Component;

class TestComponent extends Component
{
    private DependencyComponent $dependency;

    public function __construct(DependencyComponent $dependency)
    {
        $this->dependency = $dependency;
    }

    public function test()
    {
        echo $this->dependency->doit();
    }
}
и

Код: Выделить всё

<?php


namespace app\components;


use yii\base\Component;

class DependencyComponent extends Component
{
    public function doit()
    {
        return 'test';
    }
}
В конфиге в 'components' прописываем так:

Код: Выделить всё

'testComponent' => [
    'class' => \app\components\TestComponent::class,
],
В контроллере:

Код: Выделить всё

public function actionTest(\app\components\TestComponent $testComponent)
{
    $testComponent->test();
}
Спасибо за развернутый пример. Попробовал на Вашем примере, Redis подгрузило но без настроек

Код: Выделить всё

'components' => [
        'requestLimiter' => [
            'class' => common\components\limiter\RequestLimiter::class
        ],
        'redis' => [
            'class' => 'yii\redis\Connection',
            'hostname' => '***.***.***.***',
            'port' => 6379,
            'password' => '**************',
            'database' => 0,
        ],
    ],    

Код: Выделить всё

     private yii\redis\Connection $redis;

    public function __construct(Connection $redis, $config = [])
    {
        $this->redis = $redis;

        parent::__construct($config);
    }

Код: Выделить всё

/** console Controller*/
public function actionExperiment(RequestLimiter $requestLimiter){
        var_dump($requestLimiter);
}

Код: Выделить всё

object(common\components\limiter\RequestLimiter)#53 (11) {
  ["redis":"common\components\limiter\RequestLimiter":private]=>
  object(yii\redis\Connection)#54 (18) {
    ["hostname"]=>
    string(9) "localhost"
    ["redirectConnectionString"]=>
    NULL
    ["port"]=>
    int(6379)
    ["unixSocket"]=>
    NULL
    ["password"]=>
    NULL
    ["database"]=>
    int(0)

В итого зависимость получил, но Redis не дотянул настройки из конфига,конфиг в common и в console
Аватара пользователя
samdark
Администратор
Сообщения: 9489
Зарегистрирован: 2009.04.02, 13:46
Откуда: Воронеж
Контактная информация:

Re: Yii DI

Сообщение samdark »

Гм, да. Там новый создаётся. Скорее всего надо в контейнере задать определение для common\components\limiter\RequestLimiter::class. Именно в контейнере, а не в components.
Ответить