使用对象而不是数组

时间:2012-08-23 22:06:25

标签: php oop design-patterns

在以下情况下创建新对象类型而不是使用数组会更有意义:

我有一个简单的结构,有两个值:Name&年龄

$ages = array(
     array(
       'name' => 'bill',
       'age'  => 22
    ),
    array(
       'name' => 'bob',
       'age'  => 50
    ),
    // etc
);

问题是这个结构是在一个类中生成的,然后通过控制器传递,然后在另一个类中使用。

因此,感觉这两个类被绑在一起,因为必须知道在另一个类中生成的这个结构的数组键。

是否有任何设计模式可以解决这个问题?

4 个答案:

答案 0 :(得分:1)

我认为您不需要(即使存在)用于在一个类中生成对象/数据结构并在另一个类中使用它的设计模式。这是与班级合作的基本前提。此外,正如alfasin所提到的,使用对象比数组更整洁。同样在将来,如果出现这种需要,您可以与其他对象进行更好的交互。

答案 1 :(得分:1)

我会一路走来并定义一个Person模型类。像这样的东西

Class Person {

  protected _age;

  protected _name;


  public function __construct($name = null, $age = null) {
    if ($name) setName($name);
    if ($age) setAge($age);
  }

  public function getName() {
    return $this->_name;
  }

  public function setName($name) {
    return $this->_name = (string) $name;
  }

  public function getAge() {
    return $this->_age;
  }

  public function setAge($age) {
    return $this->_age = (int) $age;
  }
}

然后,您可以使用此类创建数据结构,如下所示:

$persons = array(new Person('bill', 22),new Person('bob', 50));

然后,您的控制器可以传递此数组,并在视图中使用如下:

foreach($persons as $person) {
  echo $person->getName();
  echo $person->getAge();
}

这种设计模式被称为MVC(模型视图控制器),非常受欢迎且有很好的文档记录,但我的解释不同。

对于您的简单结构,这可能看起来有些过分,但是在将来扩展代码时,它会为您节省大量时间。

(代码未经过测试,但我认为应该可以正常使用)

答案 2 :(得分:0)

由于它是一个简单的结构,你可以使用它,但一般来说,建议使用对象。如果您希望将来添加字段,添加级别(嵌套数组) - 维护将更容易,因为您的程序将更模块化,更少耦合:

// I - easier to use
$bill_age = $ages->get_age('bill'); 
// function get_age() is implemented in the class which 
// makes you code easier to maintain and easier to understand

// II - this implementation is dependent on the structure of $ages 
// if you'll change $ages - you'll have to change all the uses:
$bill_arr = $ages[0];
$bill_age = $bill_arr['age'];

此外,如果您在代码中的不同位置有II之类的电话,则更改$ages结构将导致更改所有这些位置,而如果您实施I - 您在代码中只有一个地方可以改变(在类中实现get_age($name))。

答案 3 :(得分:0)

我认为您可以拥有一个包含此结构的Keys的类,然后这两个类将共享此类以获取关键实例。 这样,您就不必跟踪两个类中的键。此外,任何时候你都可以添加更多的密钥而不需要更改。更少的耦合和更大的灵活性。

相关问题