joomla/registry

Joomla 注册表包

3.0.0 2023-10-08 14:10 UTC

README

Latest Stable Version Total Downloads Latest Unstable Version License

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

通过注册表加载配置

use Joomla\Registry\Registry;

$registry = new Registry();

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

$registry->loadString('<root></root>', 'xml');

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

// Load by file
$registry->loadFile($root . '/config/config.json', 'json');

通过getter和setter访问注册表

获取值

$registry->get('foo');

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

// OR

$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', $value);

从注册表中移除值

// 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 安装

"joomla/registry": "~3.0" 添加到 composer.json 中的 'require' 块,然后运行 composer install

{
    "require": {
        "joomla/registry": "~3.0"
    }
}

或者,你可以简单地从命令行运行以下命令

composer require joomla/registry "~3.0"