gpt4 book ai didi

laravel - 我如何做类型提示 'automatic injection' 自定义类 laravel

转载 作者:行者123 更新时间:2023-12-05 05:16:51 25 4
gpt4 key购买 nike

下面是 EmailNotifier 类

class EmailNotifier 
{
public function notify()
{
echo 'Sending payment notification via email' ;
}
}

下面是我的AppServiceProvider

 class AppServiceProvider extends ServiceProvider
{

public function boot()
{

}

public function register()
{
$this->app->make(App\EmailNotifier::class); // resolve the EmailNotifier Class
}

}

下面是计费类

class Billing
{

protected $notifier;


public function __construct(EmailNotifier $notifier)
{
$this->notifier = $notifier;
}

public function pay()
{
// Process the bill payment
$this->notifier->notify();
}

}

在我的 Controller 中我做了

  $data = new Billing(1); 

如您所见,我已经在 AppServiceProvider 类中解析了 EmailNotifier 类,但是当我像上面的代码那样调用它时,它会抛出一个错误,提示“必须是 EmailNotifier 的一个实例”

并且根据 laravel 文档,声明:

you may "type-hint" the dependency in the constructor of a class that is resolved by the container (for the automatic injection)

如何在 laravel 中实现类型提示的自动注入(inject)?

最佳答案

使用 $data = resolve(Billing::class); 而不是 $data = new Billing(1); 你可以删除 $this->app->make(App\EmailNotifier::class);//从服务提供商的注册方法中解析 EmailNotifier 类

关于laravel - 我如何做类型提示 'automatic injection' 自定义类 laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49998608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com