服务在 MVC 中去哪里? [英] Where do services go in MVC?

查看:40
本文介绍了服务在 MVC 中去哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我问过这几个开发者,每次都得到不同的答案.

假设我在一个 MVC 框架中工作,我有一个名为 validator 的类.假设这个对象有一堆方法可以用来告诉你电子邮件或电话号码是否有效,或者给定的值是否真的包含内容.

假设我想让这个服务成为我正在创建的模型的属性.我可以简单地将它注入到我的模型类的构造方法中.但是,这个服务在 MVC 中适合什么地方?它是一个模型吗?

文件应该存储在哪里?与模型?在它自己的目录中,也许叫做 services?

解决方案

我想我对 mvc 中的模型有不同的看法 [遗憾的是没有双关语],但服务绝对应该进入模型层.

首先,模型不应该是一个类.该模型是一个模型,属于一个应用程序.应用程序在不同的事物中建模(包含在模型层中):实体、映射器、服务.

例如,这可能是代表此概念的文件层次结构:

<前>应用控制器模型实体映射器服务看法

<块引用>

假设我想让这个服务成为我正在创建的模型的属性.我可以简单地将它注入到我的模型类的构造方法中.但是,这个服务在 MVC 中适合什么地方?它是一个模型吗?

我假设模型"确实是一个Entity,一个代表域概念的对象.在这种情况下,服务应该是实体的属性.服务应该被控制器使用,去做他们被要求做的任何事情,然后映射器会根据服务所做的结果构建你的实体.

<小时>

我目前的理解很大程度上来自这个答案,你一定要阅读它以进一步理解.

I've asked this several developers, and gotten different answers every time.

Let's say I'm working in an MVC framework and I have a class called validator. Say this object has a bunch of methods which can be used to tell you if an email or phone number is valid, or if a given value actually has content in it.

Say I want to make this service a property of a model that I'm creating. I can simply inject it into the construction method of my model class. However, where does this service fit in in MVC? Is it a model?

Where should the file be stored? With the models? In it's own directory, perhaps called services?

解决方案

I think I have a different view [sadly no pun was intended] of what the Model is in mvc, but services should definitely go in the Model layer.

First, a model shouldn't be a class. The model is a model, of one application. An application is modelized in different things (contained in the Model layer): Entities, Mappers, Services.

For exemple, that could be a file hierarchy representing this concept:

application
    Controller
    Model
        Entities
        Mappers
        Services
    View

Say I want to make this service a property of a model that I'm creating. I can simply inject it into the construction method of my model class. However, where does this service fit in in MVC? Is it a model?

I'll assume "model" as you say it is indeed an Entity, an object representing a domain concept. In that case, a service should not be a property of an entity. Services should be used by Controllers, to do whatever they are called to do, then Mappers would construct your Entities from the result of what the Services did.


My current understanding vastly comes from this answer, you should definitely read it for further understanding.

这篇关于服务在 MVC 中去哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆