kapitanluffy/array-legacy

dev-master 2018-11-12 10:11 UTC

This package is auto-updated.

Last update: 2024-09-12 23:31:22 UTC


README

一个将数组转换为容错对象的类。其目的是像访问数组一样访问数组,但不需要检查键是否已“设置”。

// No more checking if the key is set
if (isset($foo['baz')) {
    $baz = $foo['baz'];
}

// No more setting a default value
if (isset($foo['bar') == false) {
    $foo['bar'] = 'default value';
}

什么是“遗留”数组?

这些是像对象一样使用的数组。在使用“遗留”代码后,我看到了很多开发者使用数组来存储数据。他们(开发者)没有麻烦创建“建模”数据的对象,因为“没有足够的时间”或“太多重构”。

使用 ArrayLegacy,我们可以避免这种情况...

注意 未定义索引:Foo 在第 5 行

用法

将数组转换为 ArrayLegacy

$foo = [
    "title" => "FooBar",
    "in_stock" => 1000,
    "price" => 100
];

$foo = ArrayLegacy::make($foo);

像数组一样使用

$foo['title'] = "FooBaz";
// Output: FooBaz
echo $foo['title'];

使用 getter/setter 方法

$foo->setInStock(999);
// Output: 999
echo $foo->getInStock();

使用 get/set 方法

$foo->set("price", 99);
// Output: 99
echo $foo->get("price");

使用 get() 你也可以指定一个默认值,如果键不存在

// Output: This is a default description
echo $foo->get("description", "This is a default description");

使用 unset() 删除键

unset($foo["title"]);
// Output: null
echo $foo["title"];

在访问/修改键时使用 mutator

// Note that mutators should directly access `attributes` property
class Foo extends ArrayLegacy {
    public function setTitle($value) {
        $this->attributes['title'] = strtolower($value);
    }

    public function getTitle() {
        return ucwords($this->attributes['title']);
    }
}

$foo = new Foo($foo);
echo $foo->setTitle("This is a test");

// Output: This Is A Test
echo $foo->getTitle();

使用 PHP 数组函数

您可以通过直接在对象中调用它来使用 数组函数

  • 具有 array_ 前缀的函数可以不带前缀调用。
  • 返回数组类型的函数将返回一个新的 ArrayLegacy 实例。
  • 通过引用传递数组的函数将修改当前实例。

不支持以下函数

  • array_combine
  • array_fill_keys
  • array_fill
  • range
  • list
  • extract
$foo = new Foo($foo);

// calls array_keys, returns a new ArrayLegacy instance of keys
$foo->keys('bar');

// calls shuffle and applies it to the current instance
$foo->shuffle();