Summary
I want to look into separating the concern of "creating a populated object from database", to use inside my application. DataMapper pattern seems to be doing just that for me.
DataMapper pattern definition: http://martinfowler.com/eaaCatalog/dataMapper.html
However, inside the DataMapper
pattern itself there are concerns of
- object management - creation, population, validation (maybe), return to caller, destruction, saving, updating etc.
- loading of the data acquired from the database (i.e. construction of SQL, sending SQL to native DB functions, receiving DB data resource, or in PHP's case an associative array of data)
- mapping of the loaded data from the database into the object's variables (schema-to-object translation, hydration, etc).
My goal as far as my application goes is to start with "I want data, give me data", and DataMapper
going "here it is, all ready for ya. And not just the data you wanted, but a whole object, already populated with the data, & mapped properly from the DB schema too!". ("Wow, thanks DataMapper!")
Question:
Can DataMapper pattern contain all of the above concerns inside a single class, or must it split each concern into their own separate classes?
Details & Some Code
Below I will focus on concerns of "data" and "object creation & population". Considering concepts such as separation of concerns, dependency injection, and object oriented programming best practices, is it appropriate for a DataMapper
pattern to contain concern of data handling? Can data concern (i.e. SQL) and concern of creating-n-populating-an-object coexist inside one class?
In example below, I have SQL (aka data concern) in my DataMapper class
class MyProductMapper
{
function getProduct()
{
$sql = "SELECT name FROM product limit 1";
$result = db_query($sql);
$data = db_fetch_array($result);
$product = new MyProduct($data);
return $product;
}
}
Should Data Concern be separated?
Consider code below as an alternative to code above (SQL extracted out of DataMapper and moved into its own data class):
//class that concerns itself with receiving some data
//creating an object, and populating that object with the data
//returning that object
class MyProductMapper
{
function getProduct()
{
$data = (new ProductData())->getNameData();
$product = new MyProduct($data);
// return product to the caller
return $product;
}
}
//class concerns itself with data retrieval functionality
class ProductData
{
function getNameData()
{
$sql = "SELECT name FROM product limit 1";
$result = db_query($sql);
$dataFromDB = db_fetch_array($result);//array('name'=>"ABC-1234");
return $dataFromDB;
}
}
I have separated the Data retrieval from object creation/object-population. Should data concern be separated from concern of of the DataMapper class, or can it coexist with others inside the same class, or does it matter at all, and one way is just as good as another?