laravel - 如何使用服务容器和服务提供者在 Laravel 服务中绑定(bind) .env 值

标签 laravel environment-variables laravel-8 laravel-service-container

我想要实现的是我有一个服务类名称“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/

相关文章:

r - 如何在R语言中展开用户和环境变量?

visual-studio - Visual Studio 脚本未正确设置环境变量

php - Laravel 8 - 未登录时如何重定向到登录页面

laravel-livewire - 输入值不适用于 Livewire 线 :model

linux - 如何将我的旧站点从共享主机服务器移动到 VPS?

php - laravel 中 whereOr 和 orWhere 的区别

python - Flask、Nginx、Gunicorn - 包导入导致 502 Bad Gateway(这是环境变量)

php - 在 Laravel 8 中运行多个 PHPUnit 测试时出错

laravel 5.5 创建数据的最佳方式

php - Laravel Eloquent 类变量文档