【问题标题】:Passing values to class constructor (variables vs array)将值传递给类构造函数(变量与数组)
【发布时间】:2017-05-18 06:56:33
【问题描述】:

我有一个名为 Items 的类,在实例化时该类应该接收 5+ 个值。 我知道将超过 (3-4) 个变量传递给构造函数表明设计不佳。

将这么多变量传递给构造函数的最佳做法是什么?

我的第一个选择:

class Items {

    protected $name;
    protected $description;
    protected $price;
    protected $photo;
    protected $type;

    public function __construct($name, $description, $price, $photo, $type)
    {
        $this->name = $name;
        $this->description = $description;
        $this->price = $price;
        $this->photo = $photo;
        $this->type = $type;
    }

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

第二个选项:

class Items {
    protected $attributes;

    public function __construct(array $attributes)
    {
        $this->attributes = $attributes;
    }

    public function name()
    {
        return $this->attributes['name'];
    }
}

【问题讨论】:

  • 您应该使用混合解决方案。将数组传递给构造函数。在构造函数extract 中,该数组并单独分配变量。提取参考php.net/manual/en/function.extract.php
  • 除了 Items 中的方法 name 之外一切正常。

标签: php oop design-patterns solid-principles


【解决方案1】:

你有很好的架构和第一个解决方案。但是,如果您的属性是动态的并且您不知道它们是什么,您可以使用第二种解决方案来实现它。在这种情况下,您可以使用修改后的第二个选项:

class Items {
    protected $attributes;

    public function __construct(array $attributes)
    {
        $this->attributes = $attributes;
    }

    public function getAttributes()
    {
        return $this->attributes;
    }
}

$items = new Items($attributes);

foreach ($items->getAttributes() as $attribute) {
    echo $attribute->name;
}

【讨论】:

  • 谢谢,我相信这是我能得到的最好的,我可以用 O(1) 时间复杂度调用 $items->getAttributes() ->name,而不是使用 O(n)每次循环。干杯:)
猜你喜欢
  • 1970-01-01
  • 2020-07-28
  • 2018-05-09
  • 2016-05-23
  • 2020-01-16
  • 1970-01-01
  • 1970-01-01
  • 2021-05-15
  • 1970-01-01
相关资源
最近更新 更多