php中的映射数组结构
我需要找到一个很好的解决方案,将一个数据库模型映射到另一个第三方模型 代码当前必须执行以下操作:php中的映射数组结构,php,Php,我需要找到一个很好的解决方案,将一个数据库模型映射到另一个第三方模型 代码当前必须执行以下操作: 'HomePhone' => $customer['details']['phone']['home'] 比如说 您可以想象,如果多次使用$customer['details']['phone']['home'],那么如果数据库发生更改(就像这样),修改密钥将成为一场噩梦 例如,我希望有一个用于映射的配置 $map = [ 'HomePhone' => 'customer.de
'HomePhone' => $customer['details']['phone']['home']
比如说
您可以想象,如果多次使用$customer['details']['phone']['home']
,那么如果数据库发生更改(就像这样),修改密钥将成为一场噩梦
例如,我希望有一个用于映射的配置
$map = [
'HomePhone' => 'customer.details.phone.home'
]
因此,我可以在整个过程中简单地使用$map['HomePhone']
,只需更改数据模型的一个位置,例如将其更改为customer.details.HomePhone
如果这是配置项的结构,我将如何在上述任务中获取customer.details.phone.home
并将其分解为[customer][details][phone][home]
这种想法是正确的,还是有更好的方法?
谢谢欢迎使用数据抽象
一般来说,如果您有一些数据,并且希望得到一段特定的数据,那么您可以编写一个选择器。好消息是,你在正确的道路上-只是你只是试图解决它有点不正确
// some data
$customer = [
// ...
'details' => [
// ...
'phone' => [
// ...
'home' => '0123456789'
]
]
];
// a selector
function customerHomePhone($customer) {
return $customer['details']['phone']['home'];
}
现在,无论何时需要在代码中访问此属性,您都将使用
<span>Home Phone: <?php echo customerHomePhone($customer) ?></span>
“它是detail
单数还是details
复数?等等,是的,我想phones
是复数,但detail
是单数……该死!”
这也意味着,你可以自由地更改家用电话数据(或任何数据)的存储位置,可以随意更改,只需在应用程序中的某个位置进行更新即可 假设您将其更改为存储为
$customer['contacts']['home_phone']
…您只需将customerHomePhone
更新到
function customerHomePhone($customer) {
return $customer['contacts']['home_phone'];
}
或者,$customer
甚至可能会发生更显著的变化。也许您将使用stdClass
而不是数组,这样选择器就变成
function customerHomePhone($customer) {
return $customer->details->phone->home;
}
没关系。只要选择器指向您正在使用的任何数据结构中的正确值,应用程序的其余部分就不会受到更改的影响,并且可以继续完美地工作
当然,构建其他选择器也是有意义的
function customerDetails($customer)
return $customer['details'];
}
function customerPhones($customer) {
return customerDetails($customer)['phone'];
}
function customerHomePhone($customer) {
return customerPhones($customer)['home'];
}
您想了解更多关于数据抽象的信息吗?查看以下链接:
function customerDetails($customer)
return $customer['details'];
}
function customerPhones($customer) {
return customerDetails($customer)['phone'];
}
function customerHomePhone($customer) {
return customerPhones($customer)['home'];
}