简短摘要:我有一个模型,我尝试注入服务,如下所示:
class Foo extends Model
{
public $bar;
public function __construct(BarServiceProvider $bar)
{
$this->bar = $bar;
}
}
它的服务提供商,如下所示:
class BarServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->singleton(BarServiceProvider::class, function($app) {
return new BarServiceProvider();
});
}
public function test()
{
echo 'Hello, Laraworld!';
}
}
它通过bootstrap/app.php
在$app->register(App\Providers\BarServiceProvider::class);
内注册,并且注册方法肯定已执行(所以从我的猜测来看,我在register()
正文中做错了什么)。但是,当我尝试通过Foo
实例化$foo = new Foo();
时,我收到一个致命的错误,即没有足够的参数传递给__construct()
方法,因此甚至无法尝试$foo->bar->test()
自然,代码甚至没有达到这一点。
我错过了什么?
附录:除了评论中提出的解决方案外,还有一个我想避免的解决方案,就是这样。在Foo的__construct()
里面,我们做了一些不可原谅的事情:
public function __construct()
{
$this->bar = new BarService();
$this->baz = new BazService();
}
从本质上讲,它确实有效,但是Laravel具有内在的魔力,使我们不会使用这些东西。