To be honest, my example was pretty bad, in fact, i missed most of the point I was trying to convey. Let me try again.
Lets say we have an abstraction layer:
PHP Code:
abstract class Database {}
class MySQLDatabase extends Database {}
class SQLiteDatabase extends Database {}
class DatabaseFactory {
public static function create($type) {
// Code to return an instance of a Database class.
}
}
Now lets assume we have a model layer:
PHP Code:
abstract class Model {}
class ExampleModel extends Model {
private $data;
public function getData() { return $this->data; }
public function setData($data) { $this->data = $data; }
}
Now lets follow Martin Fowlers DataMapper pattern and place a model specific data mapper to map the Model to the table.
PHP Code:
abstract class Mapper {}
class ExampleMapper extends Mapper {
private $model;
private $db;
public function __construct($model) {
$this->model = $model;
// Creates an instance of the DB abstraction. Therefore, Mapper composes Database
$this->db = new DatabaseFactory::create('sqlite'); // The Database "type" could here be taken from a registry, passed through a parameter etc.
}
public function insert() {
// Utilise $this->db and $this->model to map $this->model->getData() to a table or tables
}
}
Now, when we look at the controller, the controller no longer has anything to do with the database and is in fact working solely with the Data Model layer.
PHP Code:
// Controller aggregates Model (nothing new here)
$model = new ExampleModel();
$model->setData('foo');
// Controller also aggregates Mapper (this, therefore, can be considered part of the Data Model layer.
$mapper = new ExampleMapper($model);
$mapper->insert();
I'd throw together some UML to illustrate this further, but I don't have a UML editor at work.
Bookmarks