(有一個TL; DR:在底部)如何在不使用我的API服務混合存儲庫的情況下實現圖層分離?
我有一個通過MVC模式生成的PDF。我正在使用一個現有的代碼,這個代碼有點亂,但現在我看到一個模式出現了。
目前,我有一個Controller
類,裏面有很多很多獨立的函數,每頁大概有一個函數。每個功能確實是這樣的:
function showPage()
{
//get some data from repository
$data1 = $this->repository->getData1();
$data2 = $this->repository->getData2();
//pass that data to the PDF API class, aka "the view"
//and the class takes care of creating PDF pages
//with the appropriate data
$this->pdfApi->showView($data, $data2);
}
以上達到Repository
完全分離(只返回數據)時,PDF API服務(接收數據和並不需要關心或保持數據檢索構建和控制器這非常簡單,只是請求數據,並將其傳遞到PDF API,一切都很好,直到我碰到這個問題來了:。
問題
幾乎每個頁面都有一個「頁腳」風趣h消息以及需要在頁面上顯示的「提案號碼」。有時它也有其他數據。由於PDF API類本身沒有數據,所以有人必須將該數據傳遞給PDF API。作爲函數參數的一部分,我一直在將上面的信息傳遞給各個部分,但它變得不方便 - 參數太多而不能通過,而且它們混淆了代碼。
嘗試解決
爲了減少參數傳遞的混亂,在我Controller
我已經創建拉着數據(通過Repository
)爲變量,如$footerText
和$proposalNumber
,然後使用他們,我填寫PDF API自己的類屬性。這樣做的副作用是,現在我的PDF API具有直接嵌入API中的相關位數據(我認爲這是不受歡迎的,因爲數據層現在強加給API類)
到目前爲止,我已經抵制了誘惑只是將整個Repository
對象傳遞給PDF API,因爲它將完成相同的工作 - 混合數據層和API層,此外,API層將不受限制地訪問數據,這也可能是不受歡迎的。
實際的問題
當我想要清潔層分離,我的代碼堆滿了多個功能參數的傳遞。
當我將整個Repository
傳遞給我的API類時,我將數據和API層混合在一起,並且API層使用Repository
類獲得很大的自由度。
我能以某種方式實現層分離而沒有混亂或上面確定的「混合層」問題嗎?
如果你喜歡看代碼,這裏是我下面的各種嘗試失敗:)
TL的一些代碼; DR:我的各種嘗試失敗,以保持層分離或減少雜波證明是不成功的
//in Controller - Exhibit 1
//Separation achieved with only data parameter passing tying layers together
//but, too much clutter -- too many parameters
//maximum layer separation but lots of annoying data passing
$data1 = $this->repository->getData1();
....
$data24 = $this->repository->getData24();
$this->pdfApi->showView($data1, $data2, $data3, ...);
//in Controller - Exhibit 2
//Layers are mixed - my data is now tied into API
//in constructor
$data1 = $this->repository->getData1();
....
$data24 = $this->repository->getData24();
$this->pdfApi->setData1($data1);
$this->pdfApi->setData24($data24);
//inside function (API already has data as part of its own vars):
$this->pdfApi->showView();
//in Controller - Exhibit 3
//layers are mixed -- entire Repository got into my API
//in constructor
$repo = new Repository();
$this->pdfApi->setRepository($repo);
//inside function (API has full Repository access gets its own data and more):
$this->pdfApi->showView();