# ENV 环境配置

Env 仅需三步即可以实现多环境切换。

注意

在实际的开发中,我们真正的不会将线上的环境配置加入版本管理中。原因有以下:

  1. 保证线上的配置文件的信息安全。
  2. 运行时不需要每次执行env_config函数获取函数。(性能有所影响,基本可以忽略不计,作为一名有B格的程序员,需要榨取框架每一滴每一分性能)

# 安装

# 1. 在项目app/utils/Env.php

<?php

declare(strict_types=1);

namespace app\utils;

/**
 * Class Env
 */
class Env
{
    protected $env;

    /**
     * 加载配置文件.
     */
    public function __construct(string $envFile)
    {
        $str = @file_get_contents($envFile);
        $arr = explode("\n", $str);
        foreach ($arr ?? [] as $v) {
            $v = $this->parse($v);
            if ($v) {
                $this->env[$v[0]] = $v[1];
            }
        }
    }

    /**
     * 获取环境变量.
     *
     * @param  string  $key
     * @param  null  $default
     * @return null|mixed
     */
    public function get(string $key, $default = null)
    {
        return $this->env[$key] ?? $default;
    }

    /**
     * 解析加载项.
     *
     * @param  string  $str
     * @return null|array
     */
    protected function parse(string $str): ?array
    {
        $r = strpos($str, '=');
        if (! $r) {
            return null;
        }
        $key = trim(substr($str, 0, $r));
        if (! $key) {
            return null;
        }
        $j = strpos($str, '#');
        if ($j === false) {
            $val = trim(substr($str, $r + 1));
        } else {
            $val = trim(substr($str, $r + 1, $j - $r - 1));
        }
        switch ($val) {
            case 'true':
            case '(true)':
                return [$key, true];
            case 'false':
            case '(false)':
                return [$key, false];
            case 'empty':
            case '(empty)':
                return [$key, ''];
            case 'null':
            case '(null)':
                return [$key, null];
            default:
                return [$key, $val];
        }
    }
}

# 2.在function.php注册函数

//env_config
if (! function_exists('env_config')) {
    function env_config(string $key, $default = null)
    {
        global $env;

        return $env->get($key, $default);
    }
}

# 3.在web.php 中增加


//默认是生产环境
$env = 'prod';
$envFile = parse_ini_file(BASE_PATH . '/.env');
if (isset($envFile['env'])) {
    $env = $envFile['env'];
}
define('ENV', $env);
//加载配置文件
$env = new Env(BASE_PATH . '/env_dev');
上次更新: 10/27/2022, 11:18:25 AM