繁体   English   中英

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

[英]How to bind .env values in Laravel Service using Service Container and Service Provider

我想要实现的是我有一个服务 class 名称' 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
            ]);
        }
    
    }

我将此服务绑定在这样的服务容器中。

$this->app->bind(SmsServiceContract::class, SmsService::class);

问题是当我试图从.env文件中获取null时,我得到了TWILIO_SID 如何在 SmsService class 中获取.env数据?

 first time config/app.php edit add this line 'account_sid' => env('TWILIO_SID'), 'account_token' => env('TWILIO_TOKEN'), 'account_from' => env('TWILIO_FROM'), and change this line public function __contruct(){ $this->account_sid = config('app.account_sid'); $this->account_token = config('app.account_token'); $this->account_from = config('app.account_from'); $this->reciever = new Client($this->account_sid, $this->account_token); } because you are production mode runnig

要从 .env 文件访问密钥,最好的方法是通过congif/app.php文件访问它们。 在 Config/app.php 中添加这些行

 'Account_SID' => env('TWILIO_SID'),
 'Account_token' => env('TWILIO_TOKEN'),
 'Account_from' => env('TWILIO_FROM'),

SmsService中,您可以将它们访问为

     public function __contruct(){
        $this->account_sid = config('app.Account_SID');
        $this->account_token =config('app.Account_token');
        $this->account_from = config('app.Account_from');
        $this->reciever = new Client($this->account_sid, $this->account_token);
     }
    

你不应该直接在你的应用程序中访问环境变量,而只能通过配置文件。

放置这些的最佳位置是config/services.php

为 Twilio 添加一段;

    'twilio' => [
        'sid' => env('TWILIO_SID'),
        'token => env('TWILIO_TOKEN'),
        'from' => env('TWILIO_FROM'),
    ] 

然后打开修补程序并运行

>>> 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() 方法将 class 绑定到容器中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM