2017-09-14 98 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+,但当然,你是最新的,对吧? ;-)