markwalet / environment-manager
v0.2.0
2018-07-25 15:23 UTC
Requires
- php: ^7.0
Requires (Dev)
- phpunit/phpunit: ^6.0
This package is not auto-updated.
Last update: 2022-02-01 13:11:09 UTC
README
一个Laravel包,可以帮助您以编程方式编辑.env文件。
安装
您可以使用composer安装此包。
composer require markwalet/environment-manager
Laravel
尽管此包是为Laravel项目编写的,但该包也可以用于其他框架或纯PHP项目。
Laravel 5.5使用包自动发现,因此您无需注册服务提供程序。如果您想手动注册服务提供程序,请将以下行添加到您的config/app.php
文件中
MarkWalet\EnvironmentManager\EnvironmentManagerServiceProvider::class
服务提供程序也兼容Laravel Lumen。只需将以下行添加到您的bootstrap/app.php
文件中
$app->register(\MarkWalet\EnvironmentManager\EnvironmentManagerServiceProvider::class);
用法
您可以通过解析Laravel服务容器来获取环境管理器。这将为您提供一个具有正确依赖项的单例MarkWalet\EnvironmentManager\Environment
实例。
$environment = app(Environment::class);
当您不使用Laravel时,也可以手动设置Environment
类。
一旦您有一个环境实例,您就可以向环境添加行
$environment->add("FOO", "Bar")->after("OTHER_KEY");
如果您未指定新值的存放位置,则该值将添加到文件末尾。
您还可以更新环境变量
$environment->update("EXISTING_KEY", "updatedValue");
这将用updatedValue
替换EXISTING_KEY
的原始值。
所有值都将自动格式化为有效的环境值。
修改多行
当您想对文件应用多个更改时,可以使用mutate()
方法。语法与Laravel迁移中的语法非常相似
/** * Original content: * * TEST1=value1 * TEST2=value2 * TEST3=value3 */ $environment->mutate(function(EnvironmentBuilder $builder){ $builder->add('TEST4', 'escaped value'); $builder->update('TEST2', 'updated')->after('TEST3'); $builder->delete('TEST1'); }); /** * New content: * * TEST3=value3 * TEST2=updated * TEST4="escaped value" */
可用方法
以下将列出每个可用方法和其底层类。这些方法可以在Environment
类本身和修改环境时获得的EnvironmentBuilder
上调用。
方法 | 返回值 |
---|---|
add(string $key, $value = null) |
添加 |
create(string $key, $value = null) |
添加 |
set(string $key, $value = null) |
更新 |
update(string $key, $value = null) |
更新 |
move(string $key) |
移动 |
delete(string $key) |
删除 |
unset(string $key) |
删除 |
扩展构建器
您还可以通过实现自己的Change
类来扩展构建器。以下示例中我们创建了一个可以快速增加值的类
use MarkWalet\EnvironmentManager\Changes\Change; class Increment extends Change { use HasKey; function __construct(string $key) { $this->key = $key; } /** * Apply the pending change to the given content. * * @param $content * * @return mixed */ public function apply(string $content): string { $search = '/'.$this->getKey().'=(.*)/'; preg_match($search, $content, $matches); $value = $matches[1]; $replacement = $this->getKey().'='.($value + 1); return preg_replace($search, $replacement, $content); } } $environment->extend('increment', Increment::class);
扩展构建器后,我们可以通过环境对象调用它
/** * Original content: * * TEST1=value1 * INCREMENT=56 */ $environment->increment('INCREMENT'); /** * New content: * * TEST1=value1 * INCREMENT=57 */