Skip to content

Commit

Permalink
添加环境变量 env/env_file 相关函数
Browse files Browse the repository at this point in the history
  • Loading branch information
ueaner committed Oct 17, 2018
1 parent 7870b13 commit 1a2ab0a
Show file tree
Hide file tree
Showing 3 changed files with 92 additions and 0 deletions.
44 changes: 44 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ Table of Contents
* [is_json](#is_json)
* [文件目录](#文件目录)
* [mkdir_p](#mkdir_p)
* [环境变量](#环境变量)
* [env](#env)
* [env_file](#env_file)

## 字符串

Expand Down Expand Up @@ -90,3 +93,44 @@ Table of Contents

mkdir_p('/path/a/b/c');
mkdir_p('/path/a/b/c', 0777);

## 环境变量

### env

`env` 获取环境变量,允许指定默认值:

// 当没有 MYSQL_HOST 这个环境变量时,返回默认的 localhost
env('MYSQL_HOST', 'localhost');

### env_file

`env_file` 获取环境配置文件名,默认为 `.env`,如果定义了 `APP_ENV`
环境变量,则返回对应的环境文件名。

如,创建 test.php,文件内容为:

<?php
include __DIR__ . "/src/helpers.php";
echo env_file();

默认执行 `php test.php`,将输出 `.env`

php test.php
// 输出
.env

如果执行 `APP_ENV=prod php test.php`,从命令行指定环境变量 `APP_ENV=prod` 将输出 `.env.prod`

APP_ENV=prod php test.php
// 输出
.env.prod

可配合 [phpdotenv] 加载对应环境配置文件的内容,假如环境配置文件放在项目根目录
BASE_PATH 下:

(new Dotenv(BASE_PATH, env_file()))->load();

加载后便可以使用 `env` 方法获取每一个环境变量的值,便于分离环境配置和项目代码。

[phpdotenv]: https://github.com/vlucas/phpdotenv
32 changes: 32 additions & 0 deletions src/helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -186,3 +186,35 @@ function mkdir_p($path, $mode = 0755)
return (is_dir($path) or mkdir($path, $mode, true));
}
}

if (!function_exists('env')) { // @codeCoverageIgnore
/**
* Gets the value of an environment variable.
*
* @param string $key
* @param mixed $default
* @return mixed
*/
function env($key, $default = null)
{
$value = getenv($key);

return $value === false ? $default : $value;
}
}

if (!function_exists('env_file')) { // @codeCoverageIgnore
/**
* Get environment file.
*
* @param string $envFile
* @return string
*/
function env_file($envFile = '.env')
{
if (getenv('APP_ENV')) {
return $envFile . '.' . getenv('APP_ENV');
}
return $envFile;
}
}
16 changes: 16 additions & 0 deletions tests/HelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,20 @@ public function testIsJson()
$this->assertFalse(is_json('{data:123}'));
$this->assertFalse(is_json(null));
}

public function testEnv()
{
$this->assertEquals('localhost', env('SOLI_DATABASE_HOST', 'localhost'));

putenv("SOLI_DATABASE_HOST=192.168.56.102");
$this->assertEquals('192.168.56.102', env('SOLI_DATABASE_HOST'));
}

public function testEnvFile()
{
$this->assertEquals('.env', env_file());

putenv("APP_ENV=prod");
$this->assertEquals('.env.prod', env_file());
}
}

0 comments on commit 1a2ab0a

Please sign in to comment.