php - 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();
解决方案
推荐阅读
- asp.net - 如何根据asp mvc的第一个下拉列表中选择的内容过滤下拉列表?
- javascript - npx babel 没有从 babel.config.js 读取配置
- java - Hibernate:使用 @JsonSerialize 和 Converter 将 List 存储为 JSON:基本属性不应是容器
- r - 在 dplyr 问题的 mutate 调用中使用自定义 case_when 函数
- java - 使用 jar 库中的类给了我一个奇怪的 JNI 错误
- python - Selenium 无法点击网页 python 的按钮
- excel - IsEmpty 对于空范围和单元格内容为空白的范围均返回 True,如何区分?
- firebase - 如何使用 Firebase Firestore 进行一次性简单查询?
- reactjs - React 状态依赖于其他状态
- google-chrome-extension - 是否可以将自定义身份验证库注入 chrome 扩展后台脚本?