我有一个Laravel项目,我创建了一个抽象类,我的几个作业将使用它们,因为他们都需要使用相同的方法来查找一些数据来继续。
在Laravel中,作业的工作方式是构造函数接受您触发作业的任何值,并且在处理程序方法中,可以注入依赖项,如下所示:
class SomeJob extends Job implements ShouldQueue
{
public function __construct(array $someData, int $someMoreData)
{
$this->someData = $someData;
$this->someMoreData = $someMoreData;
}
public function handle()
{
// Do something...
}
}
\Queue::pushOn(Queue::getDefaultQueue(), new SomeJob([1, 2, 3], 4));
这意味着我不能仅仅从扩展类的构造函数中将依赖项传递给抽象类。我可以看到,绕过它的唯一方法是在抽象类上有一个属性,然后在扩展类的handler方法中设置它。
abstract class SomeAbstractClass extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
protected $configOne;
protected $configTwo;
protected $userRepository;
public function __construct()
{
$this->configOne = config('someConfig.valueOne');
$this->configTwo = config('someConfig.valueTwo');
}
public function doSomethingWithUserRepository()
{
return $this->userRepository->doSomething();
}
}
class SomeClass extends SomeAbstractClass
{
public function __construct(array $someData, int $someMoreData)
{
parent::__construct();
$this->someData = $someData;
$this->someMoreData = $someMoreData;
}
public function handle(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
}
这可以按预期工作,但它似乎不是正确的方法。即使它有效,它似乎有点hacky。有办法解决这个问题吗?这一定是一个非常普遍的问题,也在Laravel之外。
因为定义的构造函数用于在Laravel中的作业中传递数据,所以在这种情况下,您必须将handle()
视为“构造函数”方法。
所以考虑这个例子:
<?php
abstract class SomeAbstractClass extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
protected $configOne;
protected $configTwo;
protected $userRepository;
public function __construct()
{
$this->configOne = config('someConfig.valueOne');
$this->configTwo = config('someConfig.valueTwo');
}
public function handle(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
protected function doSomethingWithUserRepository()
{
return $this->userRepository->doSomething();
}
}
class SomeClass extends SomeAbstractClass
{
public function __construct(array $someData, int $someMoreData)
{
parent::__construct();
$this->someData = $someData;
$this->someMoreData = $someMoreData;
}
public function handle(UserRepository $userRepository)
{
parent::handle($userRepository);
// you can do whatever you liiike
$this->doSomethingWithUserRepository();
}
}