项目作者: alrik11es

项目描述 :
Object dot notation getter
高级语言: PHP
项目地址: git://github.com/alrik11es/object-dot-notation.git
创建时间: 2017-06-06T11:22:28Z
项目社区:https://github.com/alrik11es/object-dot-notation

开源协议:MIT License

下载


alt tag Build Status

  1. The idea behind this library is to allow the access through
  2. `config.port` dot notation to object data.

Why?

My main problem was when accessing API data.

  1. {
  2. "hits":{
  3. "products": [
  4. {
  5. "name": "Shoe"
  6. }
  7. ]
  8. }
  9. }

Imagine this is the result from an API. Usually to be sure that the data is what I want I’m gonna need to do:

  1. <?php
  2. $result = r(); // imagine this is the result from an API with the json message abobe
  3. if(is_object($result) && property_exists($result, 'hits')){
  4. if(is_object($result->hits) && property_exists($result->hits, 'products')){
  5. $whatiwant = $result->hits->products;
  6. }
  7. }

This is really time consuming. I just needed a way to do something like:

  1. <?php
  2. $d = \Alr\ObjectDotNotation\Data::load(r());
  3. $whatiwant = $d->get('hits.products');

Note: In PHP7 you can just use $var = $something ?? $something2; but if you need to do this dynamically it becomes harder to do.

Demo

You can try a demo here

Installation

Requires composer and PHP5.6+

$ composer require alrik11es/object-dot-notation

Usage

When the property is not found a null will be returned.

Take this object as example:

  1. {
  2. "config": {
  3. "port": "1234",
  4. "url": "testurl.com"
  5. }
  6. }

Then:

  1. <?php
  2. $d = \Alr\ObjectDotNotation\Data::load($mixed);
  3. echo $d->get('config.port'); // 1234
  4. echo $d->{'config.port'};
  5. echo $d->config; // ['port'=>1234 ...]

For other kind of uses you’re gonna need to get a position of an array or search
and get the first value of array.

Take this object as example:

  1. {
  2. "config": [{
  3. "port": "80",
  4. "url": "aurl.com"
  5. },{
  6. "port": "90",
  7. "url": "burl.com"
  8. }]
  9. }

You can use this way to access the information:

  1. <?php
  2. $d = \Alr\ObjectDotNotation\Data::load($mixed);
  3. echo $d->get('config[0].port'); // 80
  4. echo $d->{'config[port=90|first].url'}; // burl.com

Filters

You can use filters for the array selection process.

[port=90|first]

IMPORTANT NOTE: Actually you can only use |first filter, use it always because it’s going to be needed on future versions to avoid compatibility problems.

Advanced filters

TODO