how to properly embed through a property?

there is a queue

class DownloadJob extends BaseObject implements \yii\queue\JobInterface
    {
        public $service;

        public function execute($queue)
        {

            $this->service->saveData( $this->entity );

        }
    }

as you can see I wanted to embed the means DI instantiated and configured $service configuring it through the configuration in the following way:

'container' => [
    'definitions' => [
       'DownloadJob' =>
             ['service' => ['class'=>'Service']]
    ],
],

how to properly embed through a property?

You could treat your service as a component:

return [
    'components' => [
        'myService' => MyService::class,
    ],
];

And then initialize service via init():


class DownloadJob extends BaseObject implements \yii\queue\JobInterface 
{
    public $service = 'myService';

    public function init()
    {
        parent::init();
        $this->service = \yii\di\Instance::ensure($this->service, MyService::class);
    }
}

Here is an example of yii2-redis: https://github.com/yiisoft/yii2-redis/blob/master/src/Mutex.php#L95

1 Like