2016-08-17 47 views
0

我剛剛穿過此示例,但未能解析與實現綁定的接口。Laravel IoC不會自動解析接口

具有如下代碼文件:

// File: app/App/Services/Talkable.php 
<?php 

namespace App\Services; 

interface Talkable { 
    public function talk(); 
} 



// File: app/App/Services/Cat.php 
<?php 

namespace App\Services; 

use App\Services\Talkable; 

class Cat implements Talkable 
{ 
    public function talk() 
    { 
     return 'meow meow'; 
    } 
} 



// File: app/Jobs/MakeSomeNoise.php 
<?php 

namespace App\Jobs; 

use App\Jobs\Job; 
use App\Services\Talkable; 

class MakeSomeNoise extends Job 
{ 
    private $talkable; 

    public function __construct(Talkable $talkable) 
    { 
     $this->talkable = $talkable; 
    } 

    public function handle() 
    { 
     return ($this->talkable->talk()); 
    } 
} 

結合是發生在app/Providers/AppServiceProvider.php

// File: app/Providers/AppServiceProvider.php 

    ... 
    $this->app->bind('App\\Services\\Talkable', 'App\\Services\\Cat'); 

MakeSomeNoise作業從控制器

// File: any controller 

    public function makeNoises() 
    { 
     return $this->dispatch(new MakeSomeNoise); // (*) 
    } 

派遣在(* ),我預計Laravel會自動解析綁定,bu它沒有。這裏的錯誤,

Argument 1 passed to App\Jobs\MakeSomeNoise::__construct() must be an instance of App\Services\Talkable, none given, called in ... 

但是,如果我只是注入控制器的構造函數,它工作正常。

對此有何想法?

回答

0

我在代碼中的錯誤。 DI應採取handle()方法,而不是構造函數。

public function handle(Talkable $talkable) { 
    // blah lbah 
}