如何使用fluent接口对所有数据成员变量调用相同的方法


How to call the same method on all data member variables using a fluent interface

我有一个这样的类:

class example{
    private $foo  = array();
    private $bar  = array();
    public function getFoo(){
        return $this->foo;
    }
    public function getBar(){
        return $this->bar;
    }
    //for example
    public function doSomth(array $smth){
        // do somth on $smth 
        return $smth;
    }
}

我希望能够定义一个方法,该方法适用于我的类中所有具有数组类型的数据成员,比如

$exmpl = new Example();
$exmpl->getFoo()->doSmth();
//or
$exmpl->getBar()->doSmth();

我该怎么办?

不直接返回$this->foo$this->bar,而是返回一个接受数据并具有doSmth方法的对象,如:

class example{
    private $foo  = array();
    private $bar  = array();
    public function getFoo(){
        return new dosmth($this->foo);
    }
    public function getBar(){
        return new dosmth($this->bar);
    }
}
class dosmth {
    public function __construct(array $smth) {
        $this->smth = $smth;
    }
    public function doSmth() {
        echo 'do something on $this->smth';
        return $this->smth;
    }
    private $smth;
}
$exmpl = new Example();
$exmpl->getFoo()->doSmth();
$exmpl->getBar()->doSmth();

另请参见Fluent Interface。

虽然这似乎解决了上述问题,但我提醒大家,可能有更好的设计方法。具体来说,让"example"纯粹是一个数据容器,其中包含"foo"answers"bar"的访问器方法,让"dosmth"是一个助手类,您可以根据需要实例化和调用它。这将是一个等价的API调用,只是稍微多了一点类型,但将关注点在类之间清晰地分开:

$helper = new dosmth;
$exmpl  = new example;
$helper->doSmth($exmpl->getFoo());
$helper->doSmth($exmpl->getBar());

流畅的界面就像一首警笛。在它们有帮助的地方使用它们,但不要因为可以就实施它们。