传递值的正确方法

时间:2016-02-01 08:07:24

标签: php oop design-patterns

假设我们有以下类,将类Foo的对象传递给Bar构造函数而不是仅传递参数baz并更好(就oop而言) quxBar构造函数?

class Foo
{
    public $baz, $qux;

    public function __construct($baz, $qux)
    {
        $this->baz = $baz;
        $this->qux = $qux;
    }

    public function main()
    {
        $bar = new Bar($this);
        //OR
        $bar = new Bar($this->baz, $this->qux);
    }
}

3 个答案:

答案 0 :(得分:1)

如果Bar类的对象在其__constructor中具有依赖注入,则第一种情况是合理的:

class Foo
{
    public $baz, $qux;

    public function __construct($baz, $qux)
    {
        $this->baz = $baz;
        $this->qux = $qux;
    }

    public function main()
    {
        $bar = new Bar($this);
        //OR
        //$bar = new Bar($this->baz, $this->qux);
    }
}

class Bar
{
    private $fooMembers = []; 

    public function __construct(Foo $foo_object)
    {
         // just for example
         $this->$fooMembers[] = $foo_object->baz;
         $this->$fooMembers[] = $foo_object->qux;
    }
}

答案 1 :(得分:0)

在我看来,就OOP而言,传递显式依赖关系的选项要好得多:

class Foo
{
    //...

    public function main()
    {
        $bar = new Bar($this->baz, $this->qux);
    }
}

在另一种情况下,您直接实现GOD对象反模式。 Bar对象不需要Foo,需要BazQux

想象一下,您需要在Bar之外创建Foo

$baz = new Baz();
$qux = new Qux();
$foo = new Foo($baz, $qux);
$bar = new Bar($foo);       

你看到了问题吗?现在你必须创建Foo才能创建Bar。

更新:查看此帖子 - Flaw: Digging into Collaborators,它会更详细地解释为什么您更喜欢直接传递依赖项。

答案 2 :(得分:0)

通常,最好传递参数,因为它们是显式的,代码可以轻松读取。

但是,在某些情况下,参数太多或太复杂。以此为例:

public function __construct(arg1, arg2, arg3, arg4, arg5)
{
    if (arg1 == 1)
    {
        $this->property1 = arg2;
        $this->property2 = arg3;
    } else {
        $this->property1 = arg4;
        $this->property2 = arg5;
    }
}

在这种情况下,每个实例化只使用一些参数。定义构造函数会更清晰:

public function __construct(Foo $foo)
{
    if ($foo->arg1 == 1)
    {
        $this->property1 = $foo->arg2;
        $this->property2 = $foo->arg3;
    } else {
        $this->property1 = $foo->arg4;
        $this->property2 = $foo->arg5;
    }
}

它做同样的事情,但它在实例化时很容易阅读。可能存在参数方案更复杂的情况。

我建议阅读有关Builder设计模式的内容。您将找到何时将对象用作参数的示例。