問題描述
您可能聽說過胖模型/瘦控制器與瘦模型/胖控制器的區別.我最近聽說你可以在模型中的一些邏輯進入服務層的地方設置一些東西.這有多常見?你知道(或能想到)任何可以說明它的真實例子嗎?
You've probably heard of the Fat Model/Thin Controller vs. Thin Model/Fat Controller distinction. I recently heard that you can have something in between where some of the logic from the model goes into a service layer. How common is this? and do you know of (or can think of) any real examples that illustrate it?
推薦答案
Martin Fowler 描述了服務層 他的偉大著作企業應用程序架構模式的模式.如果你像你問的那樣關心問題,你應該閱讀這本書.
Martin Fowler describes the Service Layer pattern of his great book Patterns of Enterprise Application Architecture. If you care about questions like the one you asked, you should read this book.
我想到的一個用途是管理數據庫事務.有些人試圖在他們的領域模型中封裝啟動和提交事務.但是當域模型調用其他也嘗試啟動和提交數據庫事務的域模型時,他們會感到困惑.那么哪個模型真正可以決定事務是提交還是回滾?如果不同客戶以不同方式使用給定模型,您會怎么做?
One use that comes to my mind is managing database transactions. Some people try to encapsulate starting and committing transactions in their domain models. But then they get confused when domain models invoke other domain models that also try to start and commit db transactions. So which model really gets to decide if a transaction is committed or rolled back? And what do you do if a given model is used in different ways by different clients?
服務層是一個解決方案,因為您可以在該層開始和提交涉及多個領域模型的工作.
The Service Layer is a solution for this, because this is the layer in which you can start and commit work that involves multiple domain models.
至于這種情況有多普遍,我認為根本不常見.大多數使用 Zend Framework(或任何其他 PHP 或 Ruby 框架)的人剛剛從Active Record 解決一切"轉向新的閃亮的Data Mapper 解決一切".這個社區似乎每五年只學習一種新模式.他們暫時無法進入服務層.
As for how common this is, I don't think it's common at all. Most people using Zend Framework (or any other PHP or Ruby framework) have just barely moved from "Active Record solves everything" to the new shiny, "Data Mapper solves everything." It seems this community learns only one new pattern every five years. They won't get to Service Layer for a while.
來自@ktutnik 的重新評論:
Re comment from @ktutnik:
不,服務層模式與存儲庫模式不同.存儲庫是關于抽象數據庫訪問,因此您可以使用像集合這樣的數據庫.服務層是關于封裝復雜的應用程序操作.
No, the Service Layer pattern is different from Repository pattern. Repository is about abstracting database access so you can use a database like a Collection. Service Layer is about encapsulating complex application operations.
另一種思考它們的方式是它們與領域模型的關系.Repository 用于域模型和數據庫之間.而服務層使用一個或多個領域模型.
Another way of thinking about them is their relationship to the Domain Model. The Repository is used between the Domain Model and the database. Whereas the Service Layer uses one or more Domain Models.
Service Layer ---> Domain Model(s) ---> Repository ---> DBAL
這篇關于MVC + 服務層在 Zend 或 PHP 中常見嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!