What is the difference between Entity and Model in Symfony2 / Doctrine

Mirage picture Mirage · Jul 12, 2012 · Viewed 11.7k times · Source

I am going through the FOSUserBundle.

And I wanted to undertand what is the difference between Model/User.php and Entity/User.php.

Can't the Model and Entity be same?

Answer

Travis picture Travis · Jul 12, 2012

Here's the best summary on the roles and terminology of Doctrine 2.

The Entity is used by the UnitOfWork pattern in Doctrine 2.0 ORM (and in Hibernate in the Java world) and is also an object representation of a thing in the real world. It has the same attributes and methods as the record would have but it does not know about its persistence. It’s basically a POPO (plain old PHP object). This allows these classes and objects to be very lightweight.

The Model is a conceptual object representation of a thing. This term could be used for all the above. A record is a model just as an entity is or a document. The term describes an object representation of a thing.

So if you want to create a bundle with some models in it and you want your bundle to be independent of any persistence layer you would create model classes and interfaces that define the thing.

You would define and / or implement everything in there that is not specific to any persistence implementation and you would use a related entity or document class via delegation to handle the specific stuff.

This is done for example in the FOSUserBundle which defines a User model. This User model is used throughout the bundle but doesn’t have a complete implementation to access its own data (I didn’t look but I think it could be an interface only). The final implementation is done in an entity class and another in a document class so no matter whether you use MySQL or MongoDB you can still work with the same User model. You can even switch from one to the other without changing your code as it always uses the model which is independent from the entity or document.