Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

env(環境変数)ファイルを作成してみた。PHPでSNSを作成してみる#06

今回は、envファイルと仕組みを作成します。

https://hasethblog.com/it/programming/php/6543/

env(環境変数)ファイル

環境変数ファイルとは、同じ定数をローカルや開発環境、本番環境ごとに別々の値を代入するときに利用します。

例えば、ローカルと本番環境で参照するデータベースは違います。接続情報も異なります。
ソースにベタ書きというのはセキュリティ的にも良くないですし、環境によってソースが違うというのもおかしな話です。

そのため環境によって別々の値を使用する際に使われます。

では早速、環境変数ファイルを作成します。

ファイルを作成する

今回、新規で作成するファイルです。

sns_training
├── app
|   └── config
|       ├── .env
|       └── config.php
└── index.php (#5でファイルを作った場合、流用)

app > config の中に .envという隠しファイルとconfig.phpを作成します。
index.phpは環境変数が使用できるか確認用に使用します。

autoloadを使用しているため、フォルダ階層も同じようにしてください。
Composerのautoloadを追加する方法。PHPでSNSを作成してみる#04

では、それぞれのファイルに記述していきます。

.env

TEST=これはテストです。
ENV=local

上の二行のように記します。

config.php

<?php
namespace App\Config;
/*
@Envファイルコネクションクラスです。
*/
class config{
  public static function getEnv($req){
    if($req == null) return;
    $arr = "";
    $envArr = explode("\n",file_get_contents(__DIR__."/.env"));
    $envVal = [];
    foreach($envArr as $key => $val){
      $arr = explode('=',trim($val));
      $envVal += [$arr[0]=>$arr[1]];
    }
    return $envVal[$req];
   }
}
?>

中身をご説明します。

    1. 【.envファイル】を改行ごと(“\n”)に配列にする
      ["TEST=これはテストです。","ENV=local"]
    2. 【1】の配列を”=“ごとに区切り連想配列にする。
      [
        "TEST"=>"これはテストです。",
        "ENV"=>"local"
      ]
    3. getEnv引数に一致するキーの値を返す
      $envVal[$req]
      $req="ENV"とすると$envVal[$req]はlocal

index.php

シリーズで読んでいただいている方へ
 この章で記述するindex.phpは一時的な内容です。
では、envファイルの中身を出力するために以下のように記述します。
<?php 
require_once "vendor/autoload.php";
use App\Config\config;
  echo config::getEnv("TEST");
  echo "<br>";
  echo config::getEnv("ENV");
?>

出力結果:

これはテストです。
local

同じように出力されたら成功です。
autoloadについては、下記リンクに記してあるのでぜひご参考ください。
Composerのautoloadを追加する方法。PHPでSNSを作成してみる#04

 

おわりに

今回は、envファイルの作成とデータの取得方法を記しました。
スクラッチ開発ならではの内容だったかと思います。

ローカルはともかく本番環境はクラウドを使用しているケースが多いと思います。
それぞれのクラウドで設定方法を模索する必要がありますね。

ただ、学びたいからといって従量課金のクラウド(AWSやGCP,Azure)を個人で登録するには敷居が高いです。
個人で学ぶには敷居が高い一方でクラウド知識の需要は伸びてきています。
オンプレミスの環境を抜け出し大手クラウドに移行しようとしている企業は多く、
執筆時のタイムリーな内容だと森永乳業の物理サーバ群のAWS移行というニュース。

システムサポート—森永乳業の物理サーバ群のAWS移行を実行、コスト削減、運用の最適化を支援

そんな需要の高まっているクラウドのプロになりませんか?
リクナビNEXTでは、職務経歴や転職希望条件などを匿名で登録しておくと、
求人企業や転職エージェントから直接オファーが来るチャンスもあります。

転職する気はない方も市場価値を知るにはよいツールです。
ぜひ興味のある方は見てみてくださいね。
リクナビNEXTに会員登録をする

以上、ありがとうございました。

コメント

スポンサーリンク
スポンサーリンク
タイトルとURLをコピーしました