doujuanxun7167 2018-07-31 00:11
浏览 21
已采纳

将存储库接口实现到作业中

I am trying to implement an Interface into a Job but having no luck. Is it possible to implement an interface / repository within the public construct and use said interface in the handle() method of the Job?

The error I am getting is as follows:

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

Below is a basic setup of what I am trying to achieve.

Stock Controller:

public function test(){
   dispatch(new OrderCreate('hello'));
}

OrderCreate Job:

protected $order;
protected $test;

public function __construct(OrderInterface $order, $test)
{
    $this->order = $order;
    $this->test = $test;
}

public function handle()
{
    $this->order->test($this->test);
}

OrderRepository:

class OrderRepository implements OrderInterface
{
    public function test($data) {
        error_log($data);
    }
}

OrderInterface:

public function test($data);

I have had no troubles implementing this pattern into my controllers and commands but I can't seem to get it working on a Job.

  • 写回答

1条回答 默认 最新

  • dongyi9484 2018-07-31 00:41
    关注

    Nevermind, the issue was I shouldn't of been calling the interface within the __construct() but instead within handle()

    Editing for more detailed explanation.

    The __construct() of a Laravel / Lumen Job from what I can tell only accepts data and thus implementing an interface within the __constuct() will cause my above error to be thrown.

    In order to use an Interface within a job, you will need to call your interface within the handle() function.

    As an example, the following will NOT work within a Job class:

    protected $test;
    
    public function __construct(InterfaceTest $test)
    {
         $this->test = $test;
    }
    

    This is because the Job construct does not take in Interfaces, it only takes in the data you pass in from the dispatch call. In order to use your Interface within a job, you need to call the interface within the handle() function and then it will succeed and work, example:

    public function handle(InterfaceTest $test)
    {
         $test->fn();
    }
    

    This seems to only be the case when implementing on a Job. In most cases when you require an interface within a Controller or Command, you will implement within the __construct().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算