2016-12-29 125 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