2016-12-29 123 views
0

我有這樣的例子類修改陣列嵌套類

Class RealUrlConfig 
{ 
    private $domains = []; 

    public function addDomain($host, $root_id) 
    { 
     $this->domains[] = [ 
      'host' => $host, 
      'rootpage_id' => $root_id, 
     ]; 

     return $this; // <-- I added this 
    } 

    public function removeDomain($host) 
    { 
     foreach ($this->domains as $key => $item) { 
      if ($item['host'] == $host) { 
       unset($this->domains[$key]); 
      } 
     } 
    } 

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

    /** 
    * TODO: I need this 
    */ 
    public function addAlias($alias) 
    { 
     $last_modify = array_pop($this->domains); 
     $last_modify['alias'] = $alias; 

     $this->domains[] = $last_modify; 
     return $this; 
    } 
} 

現在我試圖創建一個選項,添加別名主機。我可以提供原始主機名和別名並添加到陣列,但我想這樣做沒有原始主機 - 嵌套的方法,這樣我可以這樣執行它:

$url_config = new RealUrlConfig; 

$url_config->addDomain('example.com', 1); 
$url_config->addDomain('example2.com', 2)->addAlias('www.example2.com'); 

我加了return $thisaddDomain方法,以便它返回對象,但我不明白,我怎麼知道要修改哪個數組,因爲我得到了整個對象。

我當然可以從domains數組中讀取最後一個添加的域並對其進行修改,但我不太確定這是否正確。

+0

只是爲了解,爲什麼沒有一個類域(與主機,rootpage_id和別名),然後在這個類中的addDomain做一個新的域,並返回新創建的域,而不是RealUrlConfig? –

+0

@DoktorOSwaldo在返回數組時,我不能再作爲對象的一部分進行修改,可以嗎? – Peon

+0

bcmcfc的答案正是我所推薦的。如果返回數組,則可以修改返回的數組,只需將其作爲參考返回即可。但是一個數組沒有函數addAlias。 –

回答

2

你需要一個代表域的類,並且有一個addAlias方法。然後你會返回,而不是$this

別名是域的一個屬性,所以從邏輯上講,以這種方式建模它是有意義的。

class Domain 
{ 
    // constructor not shown for brevity 

    public function addAlias($alias) 
    { 
     $this->alias = $alias; 
    }  
} 

,並在原始類:

public function addDomain($host, $root_id) 
{ 
    $domain = new Domain($host, $root_id); 

    // optionally index the domains by the host, so they're easier to access later 
    $this->domains[$host] = $domain; 
    //$this->domains[] = $domain; 

    return $domain; 
} 

如果你確實想通過主索引他們在上面的例子中,你可以把它簡化一點:

$this->domains[$host] = new Domain($host, $root_id); 
return $this->domains[$host]; 

所得在選項中:

$url_config->addDomain('example2.com', 2)->addAlias('www.example2.com'); 

理想情況下,配置類不會負責構建新的Domain對象,因爲這違反了Single Responsibility Principle。相反,你會注入一個DomainFactory對象,它有一個newDomain方法。

然後,你必須:

$this->domans[$host] = $this->domainFactory->newDomain($host, $root_id); 

addDomain方法

我已經將其與答案的其餘部分分開了,因爲依賴注入是一個稍微高級的主題。

+0

但是,如何在最後一個方法中傳遞* alias *? – Peon

+0

這可以讓你通過你想要的問題的確切方式。 – bcmcfc