digimax/dot-env-editor

用于更新.env文件的简单PHP包

v1.2.2 2024-02-04 11:08 UTC

This package is auto-updated.

Last update: 2024-09-24 15:10:02 UTC


README

一个强大的PHP包,旨在简化项目中对.env文件的管理和操作。轻松读取、写入、更新和删除环境变量。

Dot-env-editor

重要

如果您正在寻找加载/读取环境变量的方法,我们强烈推荐您使用 vlucas/phpdotenv

功能 🔥

  • 轻松加载并解析.env文件
  • 获取、设置和删除环境变量
  • 支持嵌套环境变量(例如DB_CONNECTION.host)
  • 更新现有变量或添加新变量的能力
  • 在写入之前可选择保留.env文件的备份
  • only()之类的辅助方法来获取变量子集
  • 简单的链式方法,提供流畅的接口
  • 处理布尔值和字符串等值格式
  • 在写回文件时保留空格和注释
  • 与各种框架和环境兼容,确保使用上的多样性。
  • 为PHP 8+构建,具有严格的类型检查

要求

  • PHP 8.1或更高版本

安装

通过Composer安装

composer require digimax/dot-env-editor

使用

use Digimax\DotEnvEditor\DotEnvEditor;

$envPath = __DIR__ . '/.env';

$editor = new DotEnvEditor(
    $envPath,   // the path to the.env file
    true,       // whether to keep a backup of the .env file before writing
);

// or using the static method
$editor = DotEnvEditor::load($envPath, true);

// set backup directory
$editor->setBackupDir(__DIR__ . '/backups');

// Get all variables
var_dump($editor->all());

// Get a specific variable
echo $editor->get('AUTHOR_NAME');

// Set a variable
$editor->set('AUTHOR_NAME', 'Raziul Islam');

// set multiple variables
$editor->set([
    'AUTHOR_URL' => 'https://raziul.dev',
    'AUTHOR_COUNTRY' => 'Bangladesh',
]);

// Remove a variable
$editor->remove('AUTHOR_URL');

// write back to the file
$editor->write();

您可以使用链式方法实现流畅的接口 😘

DotEnvEditor::load($envPath, true)
    ->setBackupDir(__DIR__ . '/backups')
    ->set([
        'AUTHOR_URL' => 'https://raziul.dev',
        'AUTHOR_COUNTRY' => 'Bangladesh',
    ])
    ->remove('AUTHOR_URL')
    ->write();

Laravel中使用 🔥

在您的AppServiceProvider中,将DotEnvEditor注册为单例

use Digimax\DotEnvEditor\DotEnvEditor;

public function register(): void
{
    $this->app->singleton(DotEnvEditor::class, function () {
        return DotEnvEditor::load(base_path('.env'))
            ->setBackupDir(storage_path('env-backups')) // backup directory
            ->setBackupCount(5); // only keep latest 5 backup
    });
}

在您的控制器中,您可以注入DotEnvEditor实例并使用它来更新环境变量

public function update(DotEnvEditor $envEditor)
{
    // Perform form/data validation

    // save the changes
    $envEditor
        ->set([
            'AUTHOR_URL' => 'https://raziul.dev',
            'AUTHOR_COUNTRY' => 'Bangladesh',
        ])
        ->write();
}

您觉得这个包有用吗?

如果这个包帮助您简化了工作流程,请考虑在GitHub上给它一个⭐️。您的支持将鼓励进一步的开发和完善!💖

支持

对于支持,请在GitHb上打开一个问题或提交一个pull request

许可

MIT许可证(MIT)。有关更多信息,请参阅许可文件