簡體   English   中英

Laravel AppServiceProvider 中的代碼在通過 DeployHQ 部署時停止 Composer 和構建

[英]Code in Laravel AppServiceProvider halts Composer & build when deploying via DeployHQ

我的AppServiceProvider.php文件中有以下代碼:

<?php

namespace App\Providers;

use App\Models\Setting;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {        
        if (Schema::hasTable('settings')) {
            foreach (Setting::all() as $setting) {
                Config::set('settings.'.$setting->key, $setting->value);
            }
        }
    }
}

哪個在本地工作正常,但是當我通過 DeployHQ 部署時,它會終止進程並出現以下錯誤:

SQLSTATE[HY000] [2002] 沒有這樣的文件或目錄(SQL:select * 來自 information_schema.tables,其中 table_schema = giga 和 table_name = settings 和 table_type = 'BASE TABLE')

這有點道理,構建服務器上不存在數據庫,因此無法運行檢查,因為沒有什么可檢查的。 有沒有其他方法可以在啟動時使用數據庫中的值來混合settings配置,這不會影響php artisan package:discover的運行?

我知道可能會被問到,但是.env文件等都已正確設置。 這個問題與構建服務器沒有數據庫,但文件通過管道傳輸到的服務器有數據庫有關。

編輯:為了提供更多上下文,也許可以就此給出一些建議,我只是在服務 class 中的這段代碼中真正使用了這個配置值:

public function __construct()
{
    $this->domain = config('api.domain');
    $this->apiVersion = config('api.version');
    $this->bearerToken = config('settings.bearer_token');
    $this->clientId = config('api.client_id');
    $this->clientSecret = config('api.client_secret');
}

網上的一切都建議將這些值放入配置中,但是如果它只是在這里被調用,直接從數據庫中檢索它是否可以?

問題是代碼試圖訪問數據庫中的“設置”表,而構建服務器上不存在該表。 處理此問題的一種方法是在運行訪問數據庫的代碼之前檢查應用程序是否在生產環境中運行。

可以通過Laravel提供的app()->environment() function查看當前環境。

if (app()->environment() !== 'production') {
    if (Schema::hasTable('settings')) {
        foreach (Setting::all() as $setting) {
            Config::set('settings.'.$setting->key, $setting->value);
        }
    }
}

這將確保代碼僅在應用程序不在生產環境中時運行。 這樣,代碼就不會干擾 php artisan package:discover 的運行,也不會導致構建服務器出錯。

您還可以將設置值移動到配置文件中,並在應用程序在生產環境中運行時包含它,這樣應用程序就不會在數據庫不存在時崩潰。

另一種選擇,如果你只使用這個服務 class 中的設置,你可以在構造方法中直接從數據庫中檢索它們,而不是使用 config. 這樣,您就不必擔心構建服務器上的設置是否可用,並且您仍然可以使用這些值而不必擔心它們是否存在於配置中。

public function __construct()
{
    $this->domain = config('api.domain');
    $this->apiVersion = config('api.version');
    $setting = Setting::where('key', 'bearer_token')->first();
    $this->bearerToken = $setting->value;
    $this->clientId = config('api.client_id');
    $this->clientSecret = config('api.client_secret');
}

在此版本的構造函數中,它直接從數據庫中的設置表中檢索 bearer_token 值,而不是使用配置。 api.domain、api.version、api.client_id 和 api.client_secret 值仍然從配置中檢索。

提醒一下,您應該確保您正在處理數據庫中不存在設置的情況,以避免應用程序中出現任何錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM