2016-03-28 38 views
3

我有一個這樣的類調用上的所有數據成員變量相同的方法:如何使用流利的接口

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(); 

我該怎麼辦?

+2

我沒有看到問題出在哪裏,你到底想做什麼?也許你可以添加一個具體的例子。 – Rizier123

回答

0

代替直接返回$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」和「bar」的訪問器方法的數據容器,並讓「dosmth」成爲您根據需要實例化和調用的助手類。這將是等效的API調用,這只是輕微更多的輸入,但保持類之間明顯分開的擔憂:

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

流利的接口是一個高歌猛進。在他們幫助的地方使用它們,但不要僅僅因爲可以。