IT

MVC의 비즈니스 로직

lottoking 2020. 5. 25. 22:21
반응형

MVC의 비즈니스 로직


두 가지 질문이 있습니다.

Q1. "비즈니스 로직"이 MVC 패턴에서 정확히 어디에 있습니까? 모델과 컨트롤러가 혼동됩니다.

Q2. "비즈니스 로직"이 "비즈니스 규칙"과 동일합니까? 그렇지 않다면 차이점은 무엇입니까?

작은 예를 들어 설명 할 수 있다면 좋을 것입니다.


비즈니스 규칙이 모델에 적용됩니다.

메일 링리스트에 대한 이메일을 표시한다고 가정하십시오. 사용자는 이메일 중 하나 옆에있는 "삭제"버튼을 클릭하고 컨트롤러는 모델에게 N 항목을 삭제하도록 알리고 모델이 변경된 뷰를 알립니다.

관리자의 이메일을 목록에서 제거해서는 안됩니다. 그것은 비즈니스 규칙이며 지식은 모델에 속합니다. 뷰는 결국 이 규칙을 어떻게 든 표현할 수 있습니다. 아마도 모델은 비즈니스 규칙의 기능인 "IsDeletable"속성을 노출하므로 특정 항목에 대해 뷰의 삭제 버튼이 비활성화되지만 규칙 자체는 포함되지 않습니다. 보기에서.

이 모델은 궁극적으로 데이터의 게이트 키퍼입니다. UI를 전혀 터치하지 않고도 비즈니스 로직을 테스트 할 수 있어야합니다.


무엇보다도 주먹 :
MVC 패턴과 n- 계층 기반 설계 원칙을 혼용하고 있다고 생각합니다.

MVC 접근 방식을 사용한다고해서 애플리케이션을 계층화해서는 안된다는 의미는 아닙니다.
MVC가 프레젠테이션 계층의 확장과 같은 것으로 보이면 도움이 될 수 있습니다.

프리젠 테이션이 아닌 코드를 MVC 패턴에 넣으면 곧 복잡한 디자인이 될 수 있습니다.
따라서 비즈니스 로직을 별도의 비즈니스 계층에 넣는 것이 좋습니다.

: 그냥 이것 좀 봐 가지고 다 계층 아키텍처에 대한 Wikipedia 기사

그것은 말한다을 :

오늘날 MVC와 유사한 MVP (model-view-presenter)는 더 큰 시스템 프리젠 테이션 레이어 에만 적용되는 우려 디자인 패턴의 분리입니다 .

어쨌든 ... 엔터프라이즈 웹 애플리케이션 에 대해 이야기 할 때 UI에서 비즈니스 로직 계층으로의 호출은 (프레젠테이션) 컨트롤러 내부에 배치해야합니다.

컨트롤러가 실제로 특정 리소스에 대한 호출을 처리하고 비즈니스 로직을 호출하여 데이터를 쿼리하고 데이터 (모델)를 적절한보기에 연결하기 때문입니다.

Mud는 비즈니스 규칙이 모델에 적용된다고 말했습니다.
또한 사실이지만 (프레젠테이션) 모델 (MVC의 'M')과 티어 기반 애플리케이션 디자인의 데이터 계층 모델을 혼합했습니다.
따라서 데이터베이스 관련 비즈니스 규칙 을 애플리케이션의 모델 (데이터 계층)에 배치하는 것이 유효 합니다.
그러나 특정 UI에만 적용되므로 MVC 구조 프레젠테이션 레이어의 모델에 배치해서는 안됩니다.

이 기술은 도메인 기반 디자인을 사용하는지 아니면 트랜잭션 스크립트 기반 접근 방식을 사용하는지와 무관합니다.

내가 당신을 위해 그것을 시각화하자 :


프리젠 테이션 레이어 : 모델-보기-컨트롤러


비즈니스 계층 : 도메인 로직-애플리케이션 로직


데이터 계층 : 데이터 저장소-데이터 액세스 계층


위에서 본 모델은 MVC, DDD 및 데이터베이스 독립 데이터 계층을 사용하는 응용 프로그램이 있음을 의미합니다.
이것은 더 큰 엔터프라이즈 웹 응용 프로그램을 설계하는 일반적인 방법입니다.

그러나 단순한 비 DDD 비즈니스 계층 (도메인 논리가없는 비즈니스 계층)과 특정 데이터베이스에 직접 쓰는 간단한 데이터 계층을 사용하도록 축소 할 수도 있습니다.
권장하지는 않지만 전체 데이터 계층을 삭제하고 비즈니스 계층에서 직접 데이터베이스에 액세스 할 수도 있습니다.

그게 속임수입니다 ...이 도움이되기를 바랍니다 ...

[참고 :] 또한 현재 응용 프로그램에 둘 이상의 "모델"이 있다는 사실을 알고 있어야합니다. 일반적으로 응용 프로그램의 각 계층에는 자체 모델이 있습니다. 프리젠 테이션 레이어의 모델은보기에 따라 다르지만 종종 사용 된 컨트롤과 무관합니다. 비즈니스 계층에는 "도메인 모델"이라는 모델이있을 수도 있습니다. 일반적으로 도메인 기반 접근 방식을 선택하기로 결정한 경우입니다. 이 "도메인 모델"에는 데이터와 비즈니스 로직 (프로그램의 주요 로직)이 포함되며 일반적으로 프리젠 테이션 레이어와 무관합니다. 프레젠테이션 계층은 일반적으로 특정 "이벤트"(버튼 누르기 등)에서 비즈니스 계층을 호출하여 데이터 계층에서 데이터를 읽거나 데이터 계층에 씁니다. 데이터 계층에는 일반적으로 데이터베이스와 관련된 자체 모델이있을 수 있습니다.

문제는 이것이 어떻게 MVC 개념에 적합합니까?

답변-> 그렇지 않습니다!
글쎄-그것은하지만 완전히하지는 않습니다.
MVC는 1970 년대 말에 Smalltalk-80 프로그래밍 언어를 위해 개발 된 접근 방식이기 때문입니다. 그 당시 GUI와 개인용 컴퓨터는 흔하지 않았으며 월드 와이드 웹도 발명되지 않았습니다! 오늘날의 프로그래밍 언어와 IDE는 대부분 1990 년대에 개발되었습니다. 당시 컴퓨터와 사용자 인터페이스는 1970 년대와 완전히 다릅니다.
MVC에 대해 이야기 할 때이 점을 명심해야합니다.
Martin Fowler는 MVC, MVP 및 오늘날의 GUI에 대해 매우 유용한 기사를 작성했습니다.


The term business logic is in my opinion not a precise definition. Evans talks in his book, Domain Driven Design, about two types of business logic:

  • Domain logic.
  • Application logic.

This separation is in my opinion a lot clearer. And with the realization that there are different types of business rules also comes the realization that they don't all necessarily go the same place.

Domain logic is logic that corresponds to the actual domain. So if you are creating an accounting application, then domain rules would be rules regarding accounts, postings, taxation, etc. In an agile software planning tool, the rules would be stuff like calculating release dates based on velocity and story points in the backlog, etc.

For both these types of application, CSV import/export could be relevant, but the rules of CSV import/export has nothing to do with the actual domain. This kind of logic is application logic.

Domain logic most certainly goes into the model layer. The model would also correspond to the domain layer in DDD.

Application logic however does not necessarily have to be placed in the model layer. That could be placed in the controllers directly, or you could create a separate application layer hosting those rules. What is most logical in this case would depend on the actual application.


A1: Business Logic goes to Model part in MVC. Role of Model is to contain data and business logic. Controller on the other hand is responsible to receive user input and decide what to do.

A2: A Business Rule is part of Business Logic. They have a has a relationship. Business Logic has Business Rules.

Take a look at Wikipedia entry for MVC. Go to Overview where it mentions the flow of MVC pattern.

Also look at Wikipedia entry for Business Logic. It is mentioned that Business Logic is comprised of Business Rules and Workflow.


This is an answered question, but I'll give my "one cent":

Business rules belong in the model. The "model" always consists of (logically or physically separated):

  • presentation model - a set of classes that is well suited for use in the view (it's tailored toward specific UI/presentation),
  • domain model - the UI-independent portion of the model, and
  • repository - the storage-aware portion of the "model".

Business rules live in the domain model, are exposed in a presentation-suitable form to the "presentation" model and are sometimes duplicated (or also enforced) in the "data layer".


As a couple of answers have pointed out, I believe there is some some misunderstanding of multi tier vs MVC architecture.

Multi tier architecture involves breaking your application into tiers/layers (e.g. presentation, business logic, data access)

MVC is an architectural style for the presentation layer of an application. For non trivial applications, business logic/business rules/data access should not be placed directly into Models, Views, or Controllers. To do so would be placing business logic in your presentation layer and thus reducing reuse and maintainability of your code.

The model is a very reasonable choice choice to place business logic, but a better/more maintainable approach is to separate your presentation layer from your business logic layer and create a business logic layer and simply call the business logic layer from your models when needed. The business logic layer will in turn call into the data access layer.

I would like to point out that it is not uncommon to find code that mixes business logic and data access in one of the MVC components, especially if the application was not architected using multiple tiers. However, in most enterprise applications, you will commonly find multi tier architectures with an MVC architecture in place within the presentation layer.


It does not make sense to put your business layer in the Model for an MVC project.

Say that your boss decides to change the presentation layer to something else, you would be screwed! The business layer should be a separate assembly. A Model contains the data that comes from the business layer that passes to the view to display. Then on post for example, the model binds to a Person class that resides in the business layer and calls PersonBusiness.SavePerson(p); where p is the Person class. Here's what I do (BusinessError class is missing but would go in the BusinessLayer too):enter image description here


Q1:

Business logics can be considered in two categories:

  1. Domain logics like controls on an email address (uniqueness, constraints, etc.), obtaining the price of a product for invoice, or, calculating the shoppingCart's total price based of its product objects.

  2. More broad and complicated workflows which are called business processes, like controlling the registration process for the student (which usually includes several steps and needs different checks and has more complicated constraints).

The first category goes into model and the second one belongs to controller. This is because the cases in the second category are broad application logics and putting them in the model may mix the model's abstraction (for example, it is not clear if we need to put those decisions in one model class or another, since they are related to both!).

See this answer for a specific distinction between model and controller, this link for very exact definitions and also this link for a nice Android example.

The point is that the notes mentioned by "Mud" and "Frank" above both can be true as well as "Pete"'s (business logic can be put in model, or controller, according to the type of business logic).

Finally, note that MVC differs from context to context. For example, in Android applications, some alternative definitions are suggested that differs from web-based ones (see this post for example).


Q2:

Business logic is more general and (as "decyclone" mentioned above) we have the following relation between them:

business rules ⊂ business logics


Why don't you introduce a service layer. then your controller will be lean and more readable, then your all controller functions will be pure actions. you can decompose business logic as you much as you need within service layer . code reusability is hight . no impact on models and repositories.


Model = code for CRUD database operations.

Controller = responds to user actions, and passes the user requests for data retrieval or delete/update to the model, subject to the business rules specific to an organization. These business rules could be implemented in helper classes, or if they are not too complex, just directly in the controller actions. The controller finally asks the view to update itself so as to give feedback to the user in the form of a new display, or a message like 'updated, thanks', etc.,

View = UI that is generated based on a query on the model.

There are no hard and fast rules regarding where business rules should go. In some designs they go into model, whereas in others they are included with the controller. But I think it is better to keep them with the controller. Let the model worry only about database connectivity.

참고URL : https://stackoverflow.com/questions/4415904/business-logic-in-mvc

반응형