2012-04-24 42 views
3

我的問題正是中描述的Strategy Pattern article in Doctrine documentation原則2:頁,塊,戰略模式與相關實體

  • 一個頁面實體
  • 一個頁面可以有一些塊
  • 塊可能是文本,圖像,表格,日曆,...(策略)
  • 一頁知道它包含塊,但不知道他們的行爲
  • 阻止繼承是不可能的

描述的方案(策略模式),似乎正是我需要什麼(閱讀更多信息,文章):

頁:

<?php 

namespace Page\Entity; 

class Page 
{ 
    /** 
    * @var int 
    * @Id @GeneratedValue 
    * @Column(type="integer") 
    */ 
    protected $id; 

    /** 
    * @var string 
    * @Column 
    */ 
    protected $title; 

    /** 
    * @var string 
    * @Column(type="text") 
    */ 
    protected $body; 

    /** 
    * @var Collection 
    * @OneToMany(targetEntity="Block", mappedBy="page") 
    */ 
    protected $blocks; 

    // ... 
} 

塊:

<?php 

namespace Page\Entity; 

class Block 
{ 
    /** 
    * @Id @GeneratedValue 
    * @Column(type="integer") 
    */ 
    protected $id; 

    /** 
    * @ManyToOne(targetEntity="Page", inversedBy="blocks") 
    */ 
    protected $page; 

    /** 
    * @Column 
    */ 
    protected $strategyClass; 

    /** 
    * Strategy object is instancied on postLoad by the BlockListener 
    * 
    * @var BlockStrategyInterface 
    */ 
    protected $strategyInstance; 

    // ... 

} 

策略接口:

<?php 

namespace Page\BlockStrategy; 

interface BlockStrategyInterface 
{ 
    public function setView($view); 

    public function getView(); 

    public function setBlock(Block $block); 

    public function getBlock(); 

    public function renderFrontend(); 

    public function renderBackend(); 
} 

我很容易想象如果我要顯示錶格或日曆,我的策略是什麼; 但是如果我的策略是顯示其他實體的內容呢?

塊需要知道實體類/ ID和具有在相關實體被移除被刪除。

我想在BlockListener的postLoad事件中添加entityClassentityId屬性到塊和負載相關的實體中。 但是如果相關實體不存在?我無法刪除postLoad中的塊。

所以,我想象創造的其他聽衆看去除相關實體,並刪除在聽衆闖民宅座。

但它意味着,我需要添加一個監聽器可以放置在一個區域內每個實體。

它可以工作,但它似乎很複雜......也許有人有更好的主意嗎?

回答

0

我不知道如果我深知你的問題,但如果你想要的是具有內部實體的實體,當父親被刪除刪除子實體,你也可以把實體作爲塊,並使用複合圖案。

你基本上可以用在實體和塊相同的接口,並在實體顯示功能可能是這樣的:

foreach ($block in $blocks) { 
    $block->display(); 
} 

刪除所有的孩子當您刪除父實體,你可以簡單地在實體的析構函數上做。

function __destruct() { 
    foreach ($block in $blocks) { 
    /* call a common interface function that does all that need to be done, implemented on each block */ 
    } 
} 

更多關於複合模式: http://en.wikipedia.org/wiki/Composite_pattern