Laravel筆記 — 框架設計模式
View-Presenter-Controller-Service-Repository-Model
Published in
2 min readMay 14, 2019
在小型專案中,典型的MVC架構發揮得很好,但隨著系統愈來愈複雜,必須再細分更多層,於是衍生出View-Presneter-Controller-Service-Repository-Model,6層的框架設計模式,不過這並不是Laravel預設的設計方式,所以也沒有官方標準可參考,也就產生一些值得議論的設計議題了。至於怎麼樣才是個好的設計是這篇文章希望持續探討與更進的主要問題,故本文會參考相關文章做紀錄與彙整,同時也加入自己的想法。
每個角色的責任是什麼?
由於實作方式因人而異,目前網路上似乎還沒有最佳解,故以下是我個人的實作原則,未來可能會再持續改進:
- Model:盡可能隱藏操作資料的know-how,將資料抽象化,作為一個Object Relational Mapping。
- Repository:藉由操作Model,幫助Service實現各種商務邏輯對應的資料庫操作方法。
- Service:實現商務邏輯,並且讓Controller僅需要專注在溝通上。
- Controller:作為View與商務邏輯間的溝通橋樑。
Presenter:負責“如何處理資料”
(how to handle data?) - View:負責“要給客戶看到什麼”
(What to see for customers?)
MVC框架
關於MVC框架可以參考我的另一篇文章:
我大致把前述六個Layer的職責對應到MVC架構中,小專案下的Model其實就是Business Model,包含了整個商業邏輯的實現與資料庫的操作方法。而View也不會刻意地把資料操作邏輯與資料處理方式獨立成一個Presenter,因此小專案的View往往混著一些邏輯判斷。
Web API Service
通常Web API Service僅僅是將Service送來的資料變成JSON format輸出到View上,所以有時Controller就涵蓋了Presenter的職責,View純粹只是JSON、XML等格式的資料。
Reference
- https://softwareengineering.stackexchange.com/questions/218011/how-accurate-is-business-logic-should-be-in-a-service-not-in-a-model
- https://ithelp.ithome.com.tw/articles/10027966
- https://baike.baidu.com/item/%E9%A2%86%E5%9F%9F%E6%A8%A1%E5%9E%8B
- https://www.martinfowler.com/bliki/AnemicDomainModel.html
- https://laravel.io/forum/06-17-2014-controller-service-repository-architecture
- https://stackoverflow.com/questions/5702391/mvcs-model-view-controller-service
- http://shian420.pixnet.net/blog/post/344824243-%5Blaravel%5D-artisan-%E5%BF%85%E5%AD%B8%E7%9A%84-model-%E6%A8%A1%E5%9E%8B%E8%A8%AD%E8%A8%88
- https://stackoverflow.com/questions/32731763/whats-the-best-practice-of-using-controller-service-and-repository-annotations
- https://blog.johnsonlu.org/repository-pattern-and-service-layer/