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 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题