Entity Class vs. Controller Class?

I’m making my way through the PHP & MySQL: Novice to Ninja book and I’ve come to a point where my brain cannot compute. :wink:

What exactly is the difference between an Entity Class and a Controller Class?

A controller is usually an object that is created when a certain route (ie. a URL) is visited, and whose responsibility is to load any required data (e.g. from a service or database) and load the correct UI view to pass that data to for display. It also takes any necessary user input to be passed to the model or view.

An entity, on the other hand, is an object that represents some concept in your application. Probably the most common would be a User entity, but a blogging application would most likely have Post and Comment entities too, to represent those things.


Thank you. As far as I can tell, an Entity class has to do with mapping a specific database table while a controller is more about the route as you say.

1 Like

The fact that an Entity maps to a database table is an implementation detail. The main purpose of Entity I would say is to encapsulate business logic. Like for example an order, what fields does it have? What can I do with it? Can I cancel it when it’s already been shipped? Etc.

And just because we need to be sure we can recreate those entities once our program stops (in PHP that’s after every requests, other languages handle that differently) we need to persist it some place where we can retrieve it later. Whether that’s a SQL database, NoSQL database, or even a file doesn’t really matter as far as the entity is concerned.

The controllers are there because browsers can’t talk to entities directly. So we need a layer of code that can receive HTTP requests, translate that to actions on entities, and send back the result over HTTP. That layer consists of controllers. Also note that that implies that controllers must not contain any business logic. Simple upfront validation is fine, but they should not be the ones to decide whether an order may be cancelled for example. That’s the entity’s job.

Also, normally there is a layer between the entities and controllers usually called the service layer or application layer, that has some high level knowledge of entities. But that’s probably a subject for a different thread :wink:


This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.