我的問題正是中描述的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事件中添加entityClass
和entityId
屬性到塊和負載相關的實體中。 但是如果相關實體不存在?我無法刪除postLoad中的塊。
所以,我想象創造的其他聽衆看去除相關實體,並刪除在聽衆闖民宅座。
但它意味着,我需要添加一個監聽器可以放置在一個區域內每個實體。
它可以工作,但它似乎很複雜......也許有人有更好的主意嗎?