簡體   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