2017-09-14 93 views
0

我正在生成競爭樹的插件。使用抽象類和方法組織文件的問題

所以,我主要有2種類型的比賽,SingleElimination,並Playoff

裏面SingleElimination,我有2例,SingleEliminationWithPreliminaryRoundSingleEliminationWithoutPreliminaryRound

對於每場比賽的類型,我有2種球員,團隊和競爭對手,基本上,團隊是競爭對手的集合。

所以,我試圖組織我的代碼是這樣的:

-- TreeGen : (Abstract) All the common code, and the entry point 

---- PlayOffTreeGen (Abstract extends TreeGen) 

------ PlayOffCompetitorTreeGen (extends PlayOffTreeGen) 

------ PlayOffTeamTreeGen (extends PlayOffTreeGen) 

---- SingleEliminationTreeGen (Abstract extends TreeGen) 

------ SingleEliminationTeamTreeGen (extends SingleEliminationTreeGen) 

------ SingleEliminationCompetitorTreeGen (extends SingleEliminationTreeGen) 

因此,該組織的偉大工程,我避免了很多條件語句,並在整體得到更低的複雜性,但現在,我有方法即例如在SingleEliminationCompetitorTreeGenPlayOffCompetitorTreeGen中都是重複的。

所以,我覺得這是這種架構的限制,但不知道應該如何讓它發展。

任何想法將不勝感激!

回答

0

也許你可以使用特質?作爲一個例子,我有一個表單生成庫,它使用DOMDocuments生成HTML(https://github.com/delboy1978uk/form)。

無論表單元素如何,所有這些HTML實體都可以設置屬性,所以我最終得到了重複的代碼。我解決它通過創建HasAttributeTrait

namespace Del\Form\Traits; 

trait HasAttributesTrait 
{ 
    /** @var array $attributes */ 
    private $attributes = []; 
    /** 
    * @param $key 
    * @return mixed|string 
    */ 
    public function getAttribute($key) 
    { 
     return isset($this->attributes[$key]) ? $this->attributes[$key] : null; 
    } 
    /** 
    * @param $key 
    * @param $value 
    * @return $this 
    */ 
    public function setAttribute($key, $value) 
    { 
     $this->attributes[$key] = $value; 
     return $this; 
    } 
    /** 
    * @param array $attributes 
    * @return $this 
    */ 
    public function setAttributes(array $attributes) 
    { 
     $this->attributes = $attributes; 
     return $this; 
    } 
    /** 
    * @return array 
    */ 
    public function getAttributes() 
    { 
     return $this->attributes; 
    } 
} 

然後,在曾經有私人$屬性和getter和setter任何類,現在只是說:

use Del\Form\Traits\HasAttributeTrait; 

class Whatever 
{ 
    use HasAtttributesTrait; 

    // other code here 
} 

現在你可以這樣做:

$something = new Whatever(); 
$something->setAttribute('href', $url); 

請注意,性狀只能從PHP 5.4+,但當然,你是最新的,對吧? ;-)