revinate / php-getter-setter
PHP 库,用于简化在数组和对象中获取和设置值。
1.0.0
2020-06-25 01:32 UTC
Requires
- php: >=7
- ext-json: *
Requires (Dev)
- phpunit/phpunit: ^6
This package is not auto-updated.
Last update: 2024-09-28 18:00:07 UTC
README
PHP 库,简化数组或对象中的值获取和设置
摘要
该库的核心由以下3对函数组成
get
/set
-- 使用点符号指定字段名,在数组、对象或类中获取和设置嵌套值getValue
/setValue
-- 在数组、对象或类中获取和设置值getValueByArrayPath
/setValueByArrayPath
-- 由get
和set
使用,通过指定数组中的路径来访问嵌套值
安装
使用 Composer
"require": { "revinate/php-getter-setter": "~0.2" },
用法
为了简化,请在文件顶部包含以下使用声明
use Revinate\GetterSetter as gs;
获取和设置
获取值
$name = gs\get($data, 'name');
带有默认值的获取
$name = gs\get($data, 'count', 0);
设置值
$updatedData = gs\set($data, 'count', 42);
以下是一个示例单元测试,以提供更多上下文。
public function testExampleJson() { $json = '{"name":"example","type":"json","value":22}'; $data = json_decode($json); $name = gs\get($data, 'name'); $missing = gs\get($data, 'missing'); $this->assertEquals('example', $name); $this->assertNull($missing); }
对象和数组之间的区别
使用 setValue
,当设置字段值时,对象将被更新。但是,与数组不同,因为它们是不可变的。只有 setValue
返回的数组将具有更新的字段。注意 ArrayObjects
,它们将像普通的 object
一样更新。
示例单元测试显示对象和数组之间的区别
public function testExampleArrayVsObject() { $json = '{"name":"example","type":"json","value":22}'; $object = json_decode($json); $array = (array)$object; // The object gets updated as well $newObject = gs\set($object, 'type', 'Object'); // Only the new array contains the update. $newArray = gs\set($array, 'type', 'Array'); $this->assertEquals($object, $newObject); $this->assertNotEquals($array, $newArray); }
获取和设置嵌套值
getPathValue
和 setPathValue
提供了获取和设置嵌套值的简便方法。
{ "first_name" : "Joe", "last_name" : "Rock", "address" : { "street":"1 Main St.", "city":"Little Rock", "state":"Arkansas" }, "profession":"Stone cutter" }
示例访问
$json = $this->getEmployeeJsonData(); $data = json_decode($json); $this->assertEquals('Arkansas', gs\get($data, 'address.state')); $this->assertNull(gs\get($data, 'address.zip'));
该表示法比 $data->address->state
更长,但它不会在以下地方崩溃:$data->address->zip
。
支持获取器、设置器、存在性和检查性方法。
这些函数支持获取器、设置器和许多 ORM 系统使用的魔术方法,如 Doctrine。
支持魔术方法如 __get 和 __set
示例数据类
class MagicAccessTestClass { protected $values = array(); function __get($name) { return $this->values[$name]; } function __isset($name) { return isset($this->values[$name]); } function __set($name, $value) { $this->values[$name] = $value; } }
示例用法
public function testMagicMethods() { $data = new MagicAccessTestClass(); $data->first_name = 'Joe'; $data->last_name = 'Rock'; gs\set($data, 'profession', 'Stone cutter'); gs\set($data, 'address', new MagicAccessTestClass()); gs\setPathValue($data, 'address.city', 'Little Rock'); $this->assertEquals('Joe', gs\get($data, 'first_name')); $this->assertEquals('Rock', gs\get($data, 'last_name')); $this->assertEquals('Little Rock', gs\get($data, 'address.city')); }