Browse Source

增加环境变量支持

tbphp 2 years ago
parent
commit
6bb02dedb5
6 changed files with 59 additions and 11 deletions
  1. 5 0
      .env.default
  2. 1 0
      .gitignore
  3. 0 7
      api/database.php
  4. 7 3
      api/index.php
  5. 6 1
      api/lib/Db.php
  6. 40 0
      api/lib/Env.php

+ 5 - 0
.env.default

@@ -0,0 +1,5 @@
+[database]
+host     = 127.0.0.1
+dbname   = svm
+user     = root
+password = root

+ 1 - 0
.gitignore

@@ -10,3 +10,4 @@ node_modules/
 *.ntvs*
 *.njsproj
 *.sln
+.env

+ 0 - 7
api/database.php

@@ -1,7 +0,0 @@
-<?php
-return [
-    'host'     => '127.0.0.1',
-    'dbname'   => 'svm',
-    'user'     => 'root',
-    'password' => 'gQ952429d',
-];

+ 7 - 3
api/index.php

@@ -12,13 +12,11 @@ if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
     }
     exit;
 }
+
 try {
     header('Content-Type: application/json; charset=utf-8');
     define('API_PATH', __DIR__);
 
-    // 加载公共方法
-    require 'common.php';
-
     // 注册自动加载
     spl_autoload_register(function ($class) {
         $file = API_PATH . '/' . str_replace('\\', '/', $class) . '.php';
@@ -28,6 +26,12 @@ try {
         include $file;
     });
 
+    // 加载环境变量
+    lib\Env::put();
+
+    // 加载公共方法
+    require 'common.php';
+
     /**
      * 路由分发
      */

+ 6 - 1
api/lib/Db.php

@@ -11,7 +11,12 @@ class Db
     public static function connect($config = [])
     {
         if (empty($config)) {
-            $config = include API_PATH . '/database.php';
+            $config = [
+                'host'     => Env::get('database.host'),
+                'dbname'   => Env::get('database.dbname'),
+                'user'     => Env::get('database.user'),
+                'password' => Env::get('database.password'),
+            ];
         }
 
         $name = md5(serialize($config));

+ 40 - 0
api/lib/Env.php

@@ -0,0 +1,40 @@
+<?php
+namespace lib;
+
+class Env
+{
+    public static function put()
+    {
+        $file = API_PATH . '/../.env';
+        // 加载环境变量配置文件
+        if (is_file($file)) {
+            $env = parse_ini_file($file, true);
+            foreach ($env as $key => $val) {
+                $name = strtoupper($key);
+                if (is_array($val)) {
+                    foreach ($val as $k => $v) {
+                        $item = $name . '_' . strtoupper($k);
+                        putenv("$item=$v");
+                    }
+                } else {
+                    putenv("$name=$val");
+                }
+            }
+        }
+    }
+
+    public static function get($name, $default = null)
+    {
+        $result = getenv(strtoupper(str_replace('.', '_', $name)));
+        if (false !== $result) {
+            if ('false' === $result) {
+                $result = false;
+            } elseif ('true' === $result) {
+                $result = true;
+            }
+            return $result;
+        } else {
+            return $default;
+        }
+    }
+}