eru123/venv

虚拟加载环境文件

v1.0.7 2023-11-19 02:29 UTC

This package is auto-updated.

Last update: 2024-09-19 04:13:04 UTC


README

虚拟加载环境文件并隔离到 $_ENV,以在数据上增加安全层,同时提供额外工具以提高便利性

安装

composer require eru123/venv

基本用法

.env 文件

APP_ENV=development

# variable in env file will only work if the 
# variable that was called is already defined.
# NOTE: variable will only work on .env file
DB_NAME=${APP_ENV}

index.php 文件

<?php

require_once __DIR__ . '/vendor/autoload.php';

# Protect system environment variables
# Move all system env variables to virtual env
venv_protect();

# load .env file
venv_load(__DIR__ . '/.env');

# Set app array
venv_set('app', [
    'version' => '1.0.0',
    'name' => 'php-venv',
]);

# Modify app.name value using dot notation
venv_set('app.name', 'php-venv2');

# Merge an array to virtual env
# Note: dot notation will not work on this function, and might override array values
# Note: array will be ignored if all elements are not key-value pair (can be potential bug if not used properly)
venv_merge(['key' => 'pair'], ['this array will be ignored'], ['key2' => 'pair2']);

# Get all virtual env variables
print_r(venv());

# Get app.version value using dot notation
print_r(venv('app.version'));

输出

Array
(
    [APP_ENV] => development
    [DB_NAME] => development
    [app] => Array
        (
            [version] => 1.0.0
            [name] => php-venv2
        )
    [key] => pair
    [key2] => pair2
)
1.0.0

高级用法

多键检查

如果您想要在第一个键未定义时使用主键、次键等,您可以将键以数组格式作为 venv() 函数的第一个参数传递。

$value = venv(['key1', 'key2', 'key3'], 'default value in case all 3 keys are not defined');