As I asked a question about singular/plural model naming conventions yesterday, I encountered the concept of a Domain Model. As I understand it so far, a Domain Model is simply an object which represents a an entity in my application.
To use a very simple example, something like this:
class User {
private $name;
public setName() {}
public getName() {}
}
Now, the question comes to mind, how do I populate this "Domain Model", either from some input source, of from a database or data source?
While reading about Domain Models, I came about the impression that there should be nothing more than a representation of the Domain concept in question inside of them. So now I will also need another class (DAO?) responsible for interacting with the data source, in this case a database table named "User". My DAO class will handle inserts, updates, deletes, and multiple fetches.
I came up with this approach to populating a User Domain Model from input, in this case post data, and then saving the record to the database, with a UserDAO class:
/**
* Populating Domain Model from input, and saving to database
*/
/** Instantiate User Domain Model, and populate it from input */
$user = new User();
$user->setName($_POST['name']);
/** Creating a new database record from User Domain Model */
$userdao = new UserDAO($pdo);
$userdao->insert($user);
And here is how I anticipated interacting with the database when I need to fetch data, in this case multiple user records:
/**
* Fetching data from database to populate User Domain Models in an array
*/
/** Instantiate new UserDAO object to interact with User table */
$users = new UserDAO($pdo);
$users->findAll();
$user_collection = [];
/** Loop UserDAO object set to populate user collection array */
foreach ($users as $user) {
/** Create new User domain object from row, and add to collection array */
$user = new User($user);
$user_collection[$user->name()] = $user;
}
It seems like the only real benefit here is organization.
My current iteration essentially has a User class that takes on all of the responsibilities of the UserDAO class above, and returns arrays of data from the database directly, which I then use in my "Controllers"/"Presenters" and which trickle through to my (passive) Views.
What I'm wondering is:
Am I on the right track?
Where does input validation belong? I assume it must go in Domain Model, if I am correct in my assumptions so far?
What is the benefit of using this technique, aside from helping to organize the basic concepts the application will rely and operate on? Why do I need this extra layer instead of operating directly on array results from the DB?