将存储库接口实现到作业中
Implement a Repository Interface into Job
我正在尝试将接口实现到作业中,但没有成功。是否可以在 public 构造中实现接口/存储库并在作业的 handle()
方法中使用所述接口?
我得到的错误如下:
Argument 1 passed to App\Jobs\OrderCreate::__construct() must be an instance of App\Http\Interfaces\OrderInterface, string given, called in /Users/Panoply/Sites/stock-sync/app/Http/Controllers/StockController.php on line 31
下面是我想要实现的基本设置。
库存控制器:
public function test(){
dispatch(new OrderCreate('hello'));
}
订单创建作业:
protected $order;
protected $test;
public function __construct(OrderInterface $order, $test)
{
$this->order = $order;
$this->test = $test;
}
public function handle()
{
$this->order->test($this->test);
}
订单库:
class OrderRepository implements OrderInterface
{
public function test($data) {
error_log($data);
}
}
订单接口:
public function test($data);
我在我的控制器和命令中实现这个模式没有遇到任何问题,但我似乎无法让它在工作中工作。
没关系,问题是我不应该在 __construct()
中调用接口,而是在 handle()
中调用接口
正在编辑更详细的解释。
据我所知,Laravel / Lumen 作业的 __construct()
只接受数据,因此在 __constuct()
中实现接口将导致抛出上述错误。
为了在作业中使用接口,您需要在 handle()
函数中调用您的接口。
例如,以下将不在作业class中工作:
protected $test;
public function __construct(InterfaceTest $test)
{
$this->test = $test;
}
这是因为 Job 构造不接受接口,它只接受您从 dispatch
调用传入的数据。为了在作业中使用您的接口,您需要在 handle()
函数中调用接口,然后它会成功并工作,示例:
public function handle(InterfaceTest $test)
{
$test->fn();
}
这似乎只有在作业上实施时才会出现这种情况。在大多数情况下,当您需要控制器或命令中的接口时,您将在 __construct()
中实现。
我正在尝试将接口实现到作业中,但没有成功。是否可以在 public 构造中实现接口/存储库并在作业的 handle()
方法中使用所述接口?
我得到的错误如下:
Argument 1 passed to App\Jobs\OrderCreate::__construct() must be an instance of App\Http\Interfaces\OrderInterface, string given, called in /Users/Panoply/Sites/stock-sync/app/Http/Controllers/StockController.php on line 31
下面是我想要实现的基本设置。
库存控制器:
public function test(){
dispatch(new OrderCreate('hello'));
}
订单创建作业:
protected $order;
protected $test;
public function __construct(OrderInterface $order, $test)
{
$this->order = $order;
$this->test = $test;
}
public function handle()
{
$this->order->test($this->test);
}
订单库:
class OrderRepository implements OrderInterface
{
public function test($data) {
error_log($data);
}
}
订单接口:
public function test($data);
我在我的控制器和命令中实现这个模式没有遇到任何问题,但我似乎无法让它在工作中工作。
没关系,问题是我不应该在 __construct()
中调用接口,而是在 handle()
正在编辑更详细的解释。
据我所知,Laravel / Lumen 作业的 __construct()
只接受数据,因此在 __constuct()
中实现接口将导致抛出上述错误。
为了在作业中使用接口,您需要在 handle()
函数中调用您的接口。
例如,以下将不在作业class中工作:
protected $test;
public function __construct(InterfaceTest $test)
{
$this->test = $test;
}
这是因为 Job 构造不接受接口,它只接受您从 dispatch
调用传入的数据。为了在作业中使用您的接口,您需要在 handle()
函数中调用接口,然后它会成功并工作,示例:
public function handle(InterfaceTest $test)
{
$test->fn();
}
这似乎只有在作业上实施时才会出现这种情况。在大多数情况下,当您需要控制器或命令中的接口时,您将在 __construct()
中实现。