在值对象中,为什么要使用特定的属性集和get方法?

时间:2014-10-10 18:28:11

标签: php design-patterns

在查看value-object模式时,我注意到大多数都使用单独的get和set属性函数,这些函数都很难写,并为拼写错误提供了大量机会。

是否有理由以这种方式书写,而不是通用的get / set例程?这是我正在使用的样板:

class ValueObject{
    protected $property1;
    protected $property2;
    protected $property3;

    public function get( $propname ){
        if( property_exists( "ValueObject", $propname ) ){
            return $this->$propname;
        }
    }

    public function set( $propname, $value ){
        if( property_exists( "ValueObject", $propname ) ){
            return( $this->$propname = $value );
        }
    }
}

1 个答案:

答案 0 :(得分:1)

getter和setter背后的想法非常有趣。

假设我们有一个用户对象,其中包含用户名,名字,姓氏和年龄,就像这样

class User()
{
public $username = 'special!';
public $firstname= 'johnny';
public $lastname = 'frecko';
public $age = 55;
}

一切都很好,假设我们在$user变量中创建了一个新对象,我们很乐意调用$user->age来获取并设置名称。

现在,稍后,你决定出于特殊原因,你想根据公式设置用户的年龄,公式取决于用户自己的年龄!

在我们的小演习中,用户的年龄是他的实际年龄减去他名字的长度!

您无法修改程序中的其他方法,它们全部连接在一起,您无法在不重写所有内容的情况下创建新的实例变量,那么您如何做?

你从“开始”中写下了一个吸气剂。像

这样的东西
function getAge()
{
    return $this->age;
}

这是微不足道的,写起来很无聊。但是现在如果我们需要为整个程序修复年龄变量,解决方案就像在getter中添加一些代码一样简单:

function getAge()
{
    return $this->age - strlen($this->firstname);
}

我们不需要实际重写任何内容,只需要这一小段代码。 在你意识到自己需要它们之前写下getter和setter的原因是因为我们人类在提前规划时非常糟糕,这为你提供了一个很好的窗口来进一步添加一些更多的计划外代码。