方法注入 - 不在控制器中?

时间:2016-12-08 15:49:13

标签: laravel laravel-5 inversion-of-control laravel-5.3

在一个类中,我希望注入一个接口并让IOC解决它。

public function handle(\some\interface $foo){

    $foo->bar();
}

以上不起作用。

2 个答案:

答案 0 :(得分:0)

您可以将接口注入到这样的类中:

interface ConnectionInjector{
    public function injectConnection( Connection $con );
}

class UserProvider implements ConnectionInjector{
    protected $connection;

    public function __construct(){
        ...
    }

    public function injectConnection( Connection $con ){
        $this->connection = $con;
    }
}

希望这有帮助!

答案 1 :(得分:-1)

如果您想要一种将接口绑定到实现的方法,那么您可以在register类的App\Providers\AppServiceProvider方法中执行此操作:

$this->app->bind('some\interface', 'some/class_implementation');

来自Docs

  

服务容器的一个非常强大的功能是它能够将接口绑定到给定的实现。例如,假设我们有一个EventPusher接口和一个RedisEventPusher实现。一旦我们编写了此接口的RedisEventPusher实现,我们就可以将其注册到服务容器中,如下所示:

$this->app->bind(
    'App\Contracts\EventPusher',
    'App\Services\RedisEventPusher'
);
  

该语句告诉容器它应该注入   RedisEventPusher当一个类需要EventPusher的实现时。   现在我们可以在构造函数中键入提示EventPusher接口,或者   服务注入依赖项的任何其他位置   容器:

use App\Contracts\EventPusher;

/**
 * Create a new class instance.
 *
 * @param  EventPusher  $pusher
 * @return void
 */
public function __construct(EventPusher $pusher)
{
    $this->pusher = $pusher;
}