DDD and MVC: Difference between 'Model' and 'Entity'

25,021

Solution 1

Entity

Entity means an object that is a single item that the business logic works with, more specifically those which have an identity of some sort.
Thus, many people refer to ORM-mapped objects as entities.

Some refer to as "entity" to a class an instance of which represents a single row in a database.

Some other people prefer to call only those of these classes as "entity" which also contain business rules, validation, and general behaviour, and they call the others as "data transfer objects".

Model

A Model is something that is not directly related to the UI (=View) and control flow (=Controller) of an application, but rather about the way how data access and the main data abstraction of the application works.

Basically, anything can be a model that fits the above.

MVC

You can use entities as your models in MVC. They mean two different things, but the same classes can be called both.

Examples

  • A Customer class is very much an entity (usually), and you also use it as part of data access in your app. It is both an entity and a model in this case.
  • A Repository class may be part of the Model, but it is clearly not an entity.
  • If there is a class that you use in the middle of your business logic layer but don't expose to the rest of the application, it may be an entity, but it is clearly not a Model from the perspective of the MVC app.

Your example

As for your code examples, I would prefer the first one.
A Model is a class that is used as a means of data abstaction of an application, not a class which has a name suffixed with "Model". Many people consider the latter bloatware.

You can pretty much consider your Repository class as part of your model, even if its name isn't suffixed with "Model".

I would add to that the fact that it is also easier to work with the first one, and for other people who later may have to understand your code, it is easier to understand.

Solution 2

All answers are a heavy mashup of different things and simply wrong.

A model in DDD is much like a model in the real world: A simplification and abstraction of something. No less and no more. It has nothing to do with data nor objects or anything else. It's simply the concept of a domain part. And in also every complex domain there is always more than one model, e.g. Trading, Invoicing, Logistics.

An entity is not a "model with identity" but simply an object with identity.

A repository is not just a 1st level cache but a part of the domain too. It is giving an illusion of in-memory objects and responsible for fetching Aggregates (not entities!) from anywhere and saving them i.e. maintaining the life cycle of objects.

Solution 3

The "model" in your application is the bit which holds your data. The "entity" in domain-driven design is, if I remember correctly, a model with an identity. That is to say, an entity is a model which usually corresponds directly to a "physical" element in a database or file. I believe DDD defines two types of models, one being the entity, the other being the value, which is just a model without and identity.

The Repository pattern is just a type of indexed collection of models/entities. So for instance if your code wants order #13, it will first ask the repository for it, and if it can't get it from there, it will go and fetch it from wherever. It's basically a level 1 cache if you will. There is no difference in how it acts with a model, and how it acts with an entity, but since the idea of a repository is to be able to fetch models using their IDs, in terms of DDD, only entities would be allowed into the repository.

Solution 4

A simple solution using service and collection:

<?php
class MyController {
    public function index() {
        $postService = ServiceContainer::get('Post');
        $postCollection = $postService->findAllByDateRange('within 30 days');
        while($postCollection->getNext()) {
            echo $postCollection->current()->getAuthor();
        }
    }
}

EDIT: The model(class) is the simple representation of the entity scheme. The model(object) is a single entity. The service operates on models and provides concrete data to the controllers. No controller has any model. The models stand alone.
On the other "side", mappers map the models into persistance layers (e.g: databases, 3rd party backends, etc).

Solution 5

while this is specifically about Ruby on Rails, the same principles and information still apply since the discussion is around MVC and DDD.

http://blog.scottbellware.com/2010/06/no-domain-driven-design-in-rails.html

Share:
25,021
Nathan Loding
Author by

Nathan Loding

Updated on July 05, 2022

Comments

  • Nathan Loding
    Nathan Loding almost 2 years

    I'm seriously confused about the concept of the 'Model' in MVC. Most frameworks that exist today put the Model between the Controller and the database, and the Model almost acts like a database abstraction layer. The concept of 'Fat Model Skinny Controller' is lost as the Controller starts doing more and more logic.

    In DDD, there is also the concept of a Domain Entity, which has a unique identity to it. As I understand it, a user is a good example of an Entity (unique userid, for instance). The Entity has a life-cycle -- it's values can change throughout the course of the action -- and then it's saved or discarded.

    The Entity I describe above is what I thought Model was supposed to be in MVC? How off-base am I?

    To clutter things more, you throw in other patterns, such as the Repository pattern (maybe putting a Service in there). It's pretty clear how the Repository would interact with an Entity -- how does it with a Model?

    Controllers can have multiple Models, which makes it seem like a Model is less a "database table" than it is a unique Entity.

    UPDATE: In this post the Model is described as something with knowledge, and it can be singular or a collection of objects. So it's sound more like an Entity and a Model are more or less the same. The Model is an all encompassing term, where an Entity is more specific. A Value Object would be a Model as well. At least in terms of MVC. Maybe???

    So, in very rough terms, which is better?

    No "Model" really ...

    class MyController {
        public function index() {
            $repo = new PostRepository();
            $posts = $repo->findAllByDateRange('within 30 days');
            foreach($posts as $post) {
                echo $post->Author;
            }
        }
    }
    

    Or this, which has a Model as the DAO?

    class MyController {
        public function index() {
            $model = new PostModel();
            // maybe this returns a PostRepository?
            $posts = $model->findAllByDateRange('within 30 days');
            while($posts->getNext()) {
                echo $posts->Post->Author;
            }
        }
    }
    

    Both those examples didn't even do what I was describing above. I'm clearly lost. Any input?

  • Nathan Loding
    Nathan Loding almost 14 years
    OK, just putting a Factory in there. But what the heck is the Model in that?
  • Nathan Loding
    Nathan Loding almost 14 years
    I think what I'm asking is this: Is the 'Model' in these examples the singular Post object that contains the "Author" variable? Or is the Model something higher level?
  • Nathan Loding
    Nathan Loding over 13 years
    There's no reason to be harsh in your last sentence: I was asking for clarification on just that. I had read the basics, but there was no help to be found so I asked. Your answer is the same as erenon's in essence; a model is a representation of something in the domain. Models are objects, but not all objects are models. A square is a rectangle ...
  • sleske
    sleske almost 13 years
    The answer is good, but I concur with Nathan - please try to be civil, being harsh is strongly discouraged.
  • hanzolo
    hanzolo over 11 years
    The link ThinkDDD requires login, and i'm not that interested anyways, and your explanation is just about as right / wrong as the rest. you should provide some concrete implementations of your statements
  • Seph
    Seph about 10 years
    There really isn't any place for that kind of 'stuffed shirt' attitude at SO. Please be civil.
  • inf3rno
    inf3rno over 9 years
    @Don Zampano : I agree with you about reading the basics. Can you give me a non-broken link, when I can get reliable information about that? ;-)
  • Jimbo
    Jimbo over 9 years
    The model is a layer. There is no such thing as a "User Model", for example.
  • Jimbo
    Jimbo over 9 years
    Apart from DDD, thank you for clarifying what so many people spout crap about: the model is a layer. You don't have "user models", you will have a user entity.
  • DavidRR
    DavidRR about 7 years
    @Jimbo If the model is a layer, could we take this further and say that there is a one-to-many relationship between the application model and its entities? For instance, from this answer: "...The Model is the representation of the data, the classes (and by extension the objects) that encapsulate the entities in your application."
  • Jimbo
    Jimbo about 7 years
    The model layer contains entities and many other objects. "MVC" doesn't exist in the classical form in a web context, which confuses me because he has a very high rep and comes from the Nerdery (decent bunch of programmers or so I've heard :-)). We don't have MVC in PHP and it's important to draw this into the forefront of discussion.
  • kmuenkel
    kmuenkel almost 4 years
    Take this with a grain of salt, I'm just learning this pattern as well. But I'm starting to wonder if the term 'Model' conflates two or three similar but separate concepts, especially in Laravel. 1) the abstraction of how to interact with a database table. 2) The response struct representing a single record therein. 3) A general layer in which any class representing a dataset of some kind could be referred to as a Model. So to properly answer this quest, I feel like you first need to define your context.