iT邦幫忙

0

Laravel 讀取設定檔

.env

讀取全部內容

  • $_ENV
Route::get('test', function(){
  return $_ENV;
});

http://localhost/test 執行結果 (view)

{"APP_NAME":"Laravel","APP_ENV":"local","APP_KEY":"base64:WlasT5Q4ICJ0xIQqSB0V5GuWYAVtLPrFEn4Hnwm1JAE=","APP_DEBUG":"true","APP_LOG_LEVEL":"debug","APP_URL":"http:\/\/localhost","DB_CONNECTION":"mysql","DB_HOST":"127.0.0.1","DB_PORT":"3306","DB_DATABASE":"homestead","DB_USERNAME":"homestead","DB_PASSWORD":"secret","BROADCAST_DRIVER":"log","CACHE_DRIVER":"file","SESSION_DRIVER":"file","QUEUE_DRIVER":"sync","REDIS_HOST":"127.0.0.1","REDIS_PASSWORD":"null","REDIS_PORT":"6379","MAIL_DRIVER":"smtp","MAIL_HOST":"smtp.mailtrap.io","MAIL_PORT":"2525","MAIL_USERNAME":"null","MAIL_PASSWORD":"null","MAIL_ENCRYPTION":"null","PUSHER_APP_ID":"","PUSHER_APP_KEY":"","PUSHER_APP_SECRET":""}

讀取指定變數

  • env('名稱')
  • $_ENV['名稱']

以APP_ENV為例

Route::get('test', function(){
  return env('APP_ENV')."<br/>".$_ENV['APP_ENV'];
});

http://localhost/test 執行結果 (view)

local
local

config

建立範例檔 config/myconfig.php

<?php

return [
    'param1' => 'value1',
	'param2' => [
	    'param2-1' => 'value2'
	]
];

讀取設定

  • config('設定檔名.變數名')
Route::get('test', function(){
  return config('myconfig.param1')."<br/>".config('myconfig.param2.param2-1');
});

http://localhost/test 執行結果 (view)

value1
value2

修改設定

  • config(['設定檔名.變數名' => '值'])
Route::get('test', function(){
  config(['myconfig.param1' => 'newvalue']);
  return config('myconfig.param1');
});

http://localhost/test 執行結果 (view)

newvalue

引用.env內容

  • env('名稱', 預設值)
Route::get('test', function(){
  config(['myconfig.param1' => json_encode(env('APP_DEBUG', false))]);
  return config('myconfig.param1');
});

http://localhost/test 執行結果 (view)

true

使用預設值的範例

Route::get('test', function(){
  config(['myconfig.param1' => json_encode(env('APP_TEST', false))]);
  return config('myconfig.param1');
});

http://localhost/test 執行結果 (view)

false

不建議由程式直接讀取.env內容,若有因環境而異的設定存在時

  1. 將設定值放入.env
  2. 由config引用.env,並給予預設值
  3. 程式存取config

尚未有邦友留言

立即登入留言