alrik11es / object-dot-notation
PHP 的对象点符号,带键存在验证
1.1.0
2019-02-21 15:02 UTC
Requires (Dev)
- phpunit/phpunit: ^5
README
The idea behind this library is to allow the access through
`config.port` dot notation to object data.
为什么?
我主要的问题是访问 API 数据时。
{ "hits":{ "products": [ { "name": "Shoe" } ] } }
想象这是 API 的结果。通常为了确保数据是我想要的,我需要做
<?php $result = r(); // imagine this is the result from an API with the json message abobe if(is_object($result) && property_exists($result, 'hits')){ if(is_object($result->hits) && property_exists($result->hits, 'products')){ $whatiwant = $result->hits->products; } }
这非常耗时。我只需要一个方法来做类似的事情
<?php $d = \Alr\ObjectDotNotation\Data::load(r()); $whatiwant = $d->get('hits.products');
注意:在 PHP7 中,你可以直接使用 $var = $something ?? $something2;
,但如果你需要动态地做这件事,就变得困难了。
演示
安装
需要 composer 和 PHP5.6+
$ composer require alrik11es/object-dot-notation
使用方法
当属性未找到时,将返回 null
。
以这个对象为例
{ "config": { "port": "1234", "url": "testurl.com" } }
然后
<?php $d = \Alr\ObjectDotNotation\Data::load($mixed); echo $d->get('config.port'); // 1234 echo $d->{'config.port'}; echo $d->config; // ['port'=>1234 ...]
数组和数组搜索
对于其他类型的用途,你需要获取数组的位置或搜索并获取数组的第一个值。
以这个对象为例
{ "config": [{ "port": "80", "url": "aurl.com" },{ "port": "90", "url": "burl.com" }] }
你可以使用这种方法来访问信息
<?php $d = \Alr\ObjectDotNotation\Data::load($mixed); echo $d->get('config[0].port'); // 80 echo $d->{'config[port=90|first].url'}; // burl.com
过滤器
你可以使用过滤器进行数组选择过程。
[port=90|first]
重要提示:实际上你只能使用
|first
过滤器,始终使用它,因为它将在未来的版本中需要,以避免兼容性问题。
高级过滤器
待办事项