首页 > 解决方案 > PHP + Stripe API - 从点语法动态设置 php 对象值

问题描述

我正在使用 Stripe 的(相对)新的 Connect Account 功能。Stripe 返回一个“fields_needed”列表进行验证,然后我根据这些字段更新 Account 对象。这是一个非常基本的解决方案:

public function setStripeValue($field, $value, $account){
switch ($field) {
  case 'legal_entity.additional_owners.address.city':
      $account->legal_entity->additional_owners->address->city = $value;
      return $account;
    break;

  case 'legal_entity.additional_owners.address.country':
      $account->legal_entity->additional_owners->address->country = $value;
      return $account;
    break;

  case 'legal_entity.additional_owners.address.line1':
      $account->legal_entity->additional_owners->address->line1 = $value;
      return $account;
    break;

  case 'legal_entity.additional_owners.address.line2':
      $account->legal_entity->additional_owners->address->line2 = $value;
      return $account;
    break;

  // etc etc ... 50 fields or more! 

如您所见,请求始终采用格式legal_entity.additional_owners.address.city或类似格式(可以是 1 级或多个级别深),值定义始终采用格式$account->legal_entity->additional_owners->address->city或类似格式。

有没有比 switch 语句更好的递归设置这些值的方法?可以设置一个或多个字段(我多次调用此函数),字段可以嵌套任意长度。谢谢!

到目前为止尝试过:

    function get($path, $object, $value) {
        $temp = &$object;
        foreach($path as $var) {
            $temp =& $temp->$var;
        }
        $temp = $value;
    }

    $key = explode(".", $field);
    get($key, $account, $value);

这似乎更新了对象中的值,但不能很好地与 Stripes API 配合使用,必须使用 PHP 对象系统 ( ->) 进行更新,然后$account->save();

标签: phplaravelobjectstripe-payments

解决方案


推荐阅读