选择复制与基于字符串的变量(对象属性)创建

时间:2012-12-09 19:53:00

标签: php

我有这样的代码:

$something_type = $this->db
    ->where('something_type_id', $something->something_type_id)
    ->get('something_types')
    ->row();
if(!$something_type) {
  $something->type = lang('data_not_specified');
} else {
  $something->type = $something_type->something_type_name;
}

// everything is exactly the same here except for one word
$something_category = $this->db
    ->where('something_category_id', $something->something_category_id)
    ->get('something_categories')
    ->row();
if(!$something_category) {
  $something->category = lang('data_not_specified');
} else {
  $something->category = $something_category->something_category_name;
}

...

// and so on, about four times

我想到的一个解决方案是:

$classfications = array('type', 'category');
foreach ($classifications as $classification) {
  $id_property = "something_{$classificiation}_id";
  $something_classification = $this->db
      ->where("something_{$classification}_id", $something->$id_property)
      ->get("something_{$classification}s")
      ->row();
  if(!$something_classification) {
    $something->$classification = lang('data_not_specified');
  } else {
    $name_property = "something_{$classificiation}_name";
    $something->$classification = $something_classification->$name_property;
  }  
}

当然,阅读可能会导致有人适应,所以我该怎么做呢?这可能是一个非常常见的问题,但我无法将其命名,因此无法使用Google搜索。

1 个答案:

答案 0 :(得分:1)

您在寻找Inflection吗?

问题中代码片段的最大挑战是,您提供的分类具有不同的复数形式(例如,"类型"变为"类型",然而" category"成为"类别")。为了在没有变形的情况下构造这些数据,您可以创建一个嵌套数组哈希,例如,

$classifications = array(
  'type' => array(
    'plural' => 'something_types',
    'id'    => 'something_type_id',
  ),
  // etc.
);

foreach ($classifications as $singular => $data) {
  /*
   * Produces:
   * $singluar = 'type';
   * $data['plural'] = 'something_types';
   * $data['id'] = 'something_type_id';
   */
}

然而,我使用的大多数PHP框架都包含一个 Inflector 类(或类似的)来处理语言中的细微差别,这使得使用单数和复数名称一起成为问题(并且将避免使用嵌套数据结构,如上所述。)

看一下CodeIgniter's Inflector Helper,了解这会带来什么。如果您已经在使用框架(使用$db帮助器建议您可能),那么还要确保它是否支持ORM,它会自动处理这种情况。

相关问题