一个简单的参数包,使得与数组一起工作更简单

v2.0.1 2022-11-15 11:39 UTC

This package is auto-updated.

Last update: 2024-09-15 15:23:10 UTC


README

Bag 是一个简单的参数包类,使得与数组一起工作更简单。

Build Status

动机

在处理数组时,总是需要调用 isset,这可能会很麻烦。

function foo (array $data) {
    if (!isset($data['status']) || !isset($data['data']['foo'])) || $data['status'] !== 'success') {
        return false;
    }
    return $data['data']['foo'];
}

// vs

function bar (array $data) {
    $data = new Bag($data);

    if ($bag->get('status') !== 'success') {
        return false;
    }

    return $bag->get('data.foo');
}

注意:在 PHP7 中,使用 isset 三元运算符isset 的样板代码可能会大大减少。

用法

$array = [
    'foo' => 'bar',
    'hello' => 'world',
    'items' => [
        'first' => 'fizz',
        'second' => 'buzz'
    ]
];

$bag = new Adam\Bag\Bag($array);

// Get a value by key
$bag->get('foo'); // string "bar"

// Set some value by key
$bag->set('fizz', 'buzz');

// Return a default value if the key is not set
$bag->get('ziff'); // null
$bag->get('ziff', 'my_default_value'); // string "my_default_value"

// Use dot notation for multidimensional arrays
$bag->get('items.first'); // string "fizz"
$bag->set('items.third', 'foovalue');

// Get the value of an item and then remove it
$bag->pluck('foo'); // string "bar"
$bag->get('foo'); // null

// Get the raw data
$bag->all(); // array

// Empty the data
$bag->flush();

// Or just use it like an array
$bag['foo'] = 'bar';
$bag['foo']; // string "bar"
$bag->get('foo'); // string "bar"

贡献

我们欢迎对这个项目的任何贡献。您可以通过 GitHub 问题或拉取请求来贡献。

许可证

本项目采用 MIT 许可证 - 详细信息请参阅 LICENSE.txt 文件。

作者

Adam Nicholson - adamnicholson10@gmail.com