Yii2队列作业构造函数依赖注入替代方案
Yii2 queue job constructor Dependency Injection alternative
我需要在 class 中获取实现 yii\queue\Job 接口的依赖项。在完美世界中,我会做这样的事情:
public function __construct(SomeInterface $service)
{
$this->service = $service;
}
public function execute($queue)
{
$this->service->doSomething();
}
不幸的是,yii2-queue 不支持在作业处理程序构造函数中解析依赖项。现在我是这样处理的:
public function execute($queue)
{
$service = Yii::$container->get(SomeInterface::class);
$service->doSomething();
}
也许有更简洁的方法来做到这一点?
我使用工厂方法模式处理它,并从其中的 DI 容器中解析依赖项。虽然重依赖序列化存在一些问题。为了解决这个问题,我使用了简单的代理。
$this->queue->push(FooJob::create($someId));
// (...)
class FooJob implements Job
{
public $id;
private $fooService;
private $heavyService;
public function __construct(int $id, FooInterface $fooService)
{
$this->fooService = $fooService;
}
public static function create(int $id): self
{
return Yii::$container->get(static::class, [$id]);
}
public function execute(Queue $queue): void
{
$this->fooService->bar($this->id); // service available since construct
$this->heavyService->bark($this->id); // service available since first call
}
public function getHeavyService(Queue $queue): HeavyInterface
{
if (!$this->heavyService) {
$this->heavyService = Yii::$container->get(HeavyServiceInterface::class);
}
return $this->heavyService;
}
}
这种方法比我以前使用的方法更简洁。它并不完美,但有 Yii 的限制就足够了。
我需要在 class 中获取实现 yii\queue\Job 接口的依赖项。在完美世界中,我会做这样的事情:
public function __construct(SomeInterface $service)
{
$this->service = $service;
}
public function execute($queue)
{
$this->service->doSomething();
}
不幸的是,yii2-queue 不支持在作业处理程序构造函数中解析依赖项。现在我是这样处理的:
public function execute($queue)
{
$service = Yii::$container->get(SomeInterface::class);
$service->doSomething();
}
也许有更简洁的方法来做到这一点?
我使用工厂方法模式处理它,并从其中的 DI 容器中解析依赖项。虽然重依赖序列化存在一些问题。为了解决这个问题,我使用了简单的代理。
$this->queue->push(FooJob::create($someId));
// (...)
class FooJob implements Job
{
public $id;
private $fooService;
private $heavyService;
public function __construct(int $id, FooInterface $fooService)
{
$this->fooService = $fooService;
}
public static function create(int $id): self
{
return Yii::$container->get(static::class, [$id]);
}
public function execute(Queue $queue): void
{
$this->fooService->bar($this->id); // service available since construct
$this->heavyService->bark($this->id); // service available since first call
}
public function getHeavyService(Queue $queue): HeavyInterface
{
if (!$this->heavyService) {
$this->heavyService = Yii::$container->get(HeavyServiceInterface::class);
}
return $this->heavyService;
}
}
这种方法比我以前使用的方法更简洁。它并不完美,但有 Yii 的限制就足够了。