misbah/prop-monitor

这个库可以帮助您检查嵌套的PHP对象是否具有某些属性。

2.0.0 2019-01-21 07:55 UTC

This package is auto-updated.

Last update: 2024-09-21 20:51:32 UTC


README

一个简单的PHP库,用于深入嵌套PHP对象以查找特定属性。

如果您必须处理一个大的对象 😱 并希望避免多次使用 property_exists(class, property) 😏 来查找单个属性,那么它将非常有用 :).

安装

使用 composer require misbah/prop-monitor 进行安装

变更日志

  • 2.0.0

    Added get($object, array $properties) function to extract a desired value by following a path of properties & array indices.
    

用法

以下json对象被转换为StdClass

$users = {
  
  'users' : [
    {
      'name' : 'John Doe',
      'email: 'john@doe.com',
      'social': {
        'twitter': '@jdoe',
        'facebook': '@johndoe',
        'github': '@jdoegit'
      }
    }
  ] 

}

检查users数组中的第一个用户的'github'属性是否存在


<?php
  
  require './vendor/autoload.php';

  $monitor = new \PropMonitor\PropMonitor();
  
  
  
  $propertiesToCheck = ['users', 0, 'social', 'github'];
  
  // Returns true
  if($monitor->check($users, $propertiesToCheck)) // assuming that we have access to the $users object described above.
  {
    echo "Yee! John has the github property 8).";
    echo "The handle is ".$monitor->get($users, $propertiesToCheck); // This will return @jdoegit
  } else {
    echo "Oops! John isn't lucky enough to have the mighty github property :(";
  }
  

关于使用get($object, array $properties)函数的说明

如果值的提取失败,此函数将返回布尔值false。

因此,要检查失败,请使用 $result === false

如果您期望最终结果是布尔值,请使用 $result === 0$result === 1

因为此函数将最终布尔值转换为整数值。

检查users数组中的第一个用户的'tumblr'属性是否存在


<?php
  require './vendor/autoload.php';

  $monitor = new \PropMonitor\PropMonitor();
  
  
  $propertiesToCheck = ['users', 0, 'social', 'tumblr'];
  
  // Returns false 
  if($monitor->check($users, $propertiesToCheck)) // assuming that we have access to the $users object described above.
  {
    echo "Yee! John has the tumblr property 8).";
  } else {
    echo "Oops! John isn't lucky enough to have the mighty tumblr property :(";
  }
  

不同的示例


<?php
  require './vendor/autoload.php';

  $monitor = new \PropMonitor\PropMonitor();
  
  
  $propertiesToCheck = ['users', '0', 'social', 'twitter']; // Look at the mentioned array index
  
  //This will return true though the array index is defined as a string
  if($monitor->check($users, $propertiesToCheck)) // assuming that we have access to the $users object described above.
  {
    echo "Yee! John has the twitter property 8).";
  } else {
    echo "Oops! John isn't lucky enough to have the mighty twitter property :(";
  }