蛋白质 / 字典
用于通过点表示法键路径处理键值数据存储库的类
1.0.4
2019-05-29 14:39 UTC
Requires
- php: ^7.2
- proteins/map: ^1.0.0
This package is auto-updated.
Last update: 2024-08-29 04:54:51 UTC
README
蛋白质 | 字典
处理键值数据存储库
安装
composer require proteins/dictionary
通过
use Proteins\Dictionary;
构建字典
字典是一个行为类,它必须由另一个类扩展,否则值存储库将共享。
class State extends Dictionary {}
设置值
您可以通过get
方法从键路径设置值。
有效的键路径是由.
分隔的任意深度的字符串序列。
示例
测试
alpha.beta
pages.section.text_block.3
State::set('options.use_cache',false); State::set('users.whitelist',[ 'frank.ciccio', 'walter.submarine', 'pepen.spacca', ]);
获取值
您可以通过get
方法从键路径获取值。
echo State::get('users.whitelist.1'); // walter.submarine
您可以可选地传递一个默认值,当请求的键未找到时返回。如果传递了可调用对象,则返回的值将被使用。
print_r( State::get('a.test',['b'=>123]) ); // Array( [b] => 123 ) echo State::get('a.test.b'); // 123
获取所有值
您可以通过all
方法获取所有键值作为关联数组。
$all_data = State::all();
结果
Array ( [users] => Array ( [whitelist] => Array( [0] => frank.ciccio [1] => walter.submarine [2] => pepen.spacca ) ) )
清除映射
您可以通过clear
方法从映射中清除所有值。
State::clear();
合并数据
merge
方法通过传递的关联数组扩展映射。第二个可选参数将定义是否从右到左或反向合并数据(默认为false = 从左到右)。
设置初始数据
State::clear(); State::merge([ 'user' => [ 'name' => 'Simon', 'role' => 'Villain', ], ]);
Array ( [user] => Array ( [name] => Simon [role] => Villain ) )
标准合并(从左到右)
State::merge([ 'user' => [ 'name' => 'Frank', ], 'happy' => true, ]);
Array ( [user] => Array ( [name] => Frank [role] => Villain ) [happy] => 1 )
反向合并(从右到左)
State::merge([ 'user' => [ 'name' => 'Frank', ], 'happy' => true, ],true);
Array ( [user] => Array ( [name] => Simon [role] => Villain ) [happy] => 1 )
获取多个值
您可以通过传递类型为的关联数组检索多个值,从而最小化函数调用。
DESTINATION_KEY => Map_PATH
示例 :
MyService::init([
'username' => State::get('aws.username'),
'password' => State::get('aws.password'),
'from' => State::get('user.email'),
'verbose' => State::get('app.global.debug'),
]);
可以用单个调用get
写成
MyService::init( State::get([
'username' => 'aws.username',
'password' => 'aws.password',
'from' => 'user.email',
'verbose' => 'app.global.debug',
]));