在一个类中,我希望注入一个接口并让IOC解决它。
public function handle(\some\interface $foo){
$foo->bar();
}
以上不起作用。
答案 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;
}