我想要实现的是我有一个服务类名称“SmsService”
<?php
namespace App\Services;
use App\Contracts\SmsServiceContract;
use App\Models\Student;
use Twilio\Rest\Client;
class SmsService implements SmsServiceContract{
private $account_sid;
private $account_token;
private $account_from;
private $reciever;
public function __construct(){
$this->account_sid = env("TWILIO_SID");
$this->account_token = env("TWILIO_TOKEN");
$this->account_from = env("TWILIO_FROM");
$this->reciever = new Client($this->account_sid, $this->account_token);
}
public function sendSingleSms($phone_number, $message){
$this->reciever->messages->create($phone_number,[
'from' => $this->account_from,
'body' => $message
]);
}
}
我正在像这样的服务容器中绑定(bind)此服务。
$this->app->bind(SmsServiceContract::class, SmsService::class);
问题是,当我尝试从 .env
文件获取 TWILIO_SID
时,我得到了 null
。
如何在 SmsService 类中获取 .env
数据?
最佳答案
您永远不应该直接在应用程序中访问环境变量,而只能通过配置文件访问。
放置这些的最佳位置是 config/services.php
添加 Twilio 部分;
'twilio' => [
'sid' => env('TWILIO_SID'),
'token => env('TWILIO_TOKEN'),
'from' => env('TWILIO_FROM'),
]
然后打开tinker并运行
>>> config('services.twilio')
并检查值是否都按预期表示。
然后在您的服务提供商中更改对 env() 的引用以进行配置并使用点分隔的名称。例如;
public function __contruct(){
$this->account_sid = config('services.twilio.sid');
$this->account_token = config('services.twilio.token');
$this->account_from = config('services.twilio.from);
最后,确保通过服务提供者的 register() 方法将类绑定(bind)到容器中。
关于laravel - 如何使用服务容器和服务提供者在 Laravel 服务中绑定(bind) .env 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72826338/