msgframework/registry

注册包提供了一个索引键值数据存储和用于将此数据导入/导出到多种格式的API。

v1.0.2 2022-01-10 12:19 UTC

This package is auto-updated.

Last update: 2024-09-14 00:24:25 UTC


README

Latest Stable Version Total Downloads Latest Unstable Version License PHP Version Require

关于

注册包提供了一个索引键值数据存储和用于将此数据导入/导出到多种格式的API。

加载注册表

use Msgframework\Lib\Registry\Registry;

$registry = new Registry;

// Load by json string
$registry->loadString('{"foo" : "bar"}');

// Load by object or array
$registry->loadObject($object);
$registry->loadArray($array);

通过getter和setter访问注册表

获取值

$registry->get('foo');

// Get a non-exists value and return default
$registry->get('foo', 'default');

设置值

// Set value
$registry->set('bar', $value);

// Sets a default value if not already assigned.
$registry->def('bar', $default);

通过路径访问子值

$json = '{
	"parent" : {
		"child" : "Foo"
	}
}';

$registry = new Registry($json);

$registry->get('parent.child'); // return 'Foo'

$registry->set('parent.child', "Goo");

$registry->get('parent.child'); // return 'Goo'

从注册表中删除值

// Set value
$registry->set('bar', $value);

// Remove the key
$registry->remove('bar');

// Works for nested keys too
$registry->set('nested.bar', $value);
$registry->remove('nested.bar');

将注册表作为数组访问

Registry类实现了ArrayAccess,因此注册表的属性可以作为数组访问。以下是一些示例

// Set a value in the registry.
$registry['foo'] = 'bar';

// Get a value from the registry;
$value = $registry['foo'];

// Check if a key in the registry is set.
if (isset($registry['foo']))
{
	echo 'Say bar.';
}

合并注册表

使用load*方法合并两个配置文件。

$json1 = '{
    "field" : {
        "keyA" : "valueA",
        "keyB" : "valueB"
    }
}';

$json2 = '{
    "field" : {
        "keyB" : "a new valueB"
    }
}';

$registry->loadString($json1);
$registry->loadString($json2);

输出

Array(
    field => Array(
        keyA => valueA
        keyB => a new valueB
    )
)

合并另一个注册表

$object1 = '{
	"foo" : "foo value",
	"bar" : {
		"bar1" : "bar value 1",
		"bar2" : "bar value 2"
	}
}';

$object2 = '{
	"foo" : "foo value",
	"bar" : {
		"bar2" : "new bar value 2"
	}
}';

$registry1 = new Registry(json_decode($object1));
$registry2 = new Registry(json_decode($object2));

$registry1->merge($registry2);

如果您只想合并第一层,不要期望递归

$registry1->merge($registry2, false); // Set param 2 to false that Registry will only merge first level

转换为单维度

$array = array(
    'flower' => array(
        'sunflower' => 'light',
        'sakura' => 'samurai'
    )
);

$registry = new Registry($array);

// Make data to one dimension

$flatted = $registry->flatten();

print_r($flatted);

结果

Array
(
    [flower.sunflower] => light
    [flower.sakura] => samurai
)

安装

您可以使用Composer轻松安装此包。

只需使用以下命令要求此包:

$ composer require msgframework/registry