What is the best practice for adding persistence to an MVC model?
Posted
by etheros
on Stack Overflow
See other posts from Stack Overflow
or by etheros
Published on 2009-10-25T16:44:30Z
Indexed on
2010/06/06
8:32 UTC
Read the original article
Hit count: 307
I'm in the process of implementing an ultra-light MVC framework in PHP. It seems to be a common opinion that the loading of data from a database, file etc. should be independent of the Model, and I agree. What I'm unsure of is the best way to link this "data layer" into MVC.
Datastore interacts with Model
//controller
public function update()
{
$model = $this->loadModel('foo');
$data = $this->loadDataStore('foo', $model);
$data->loadBar(9); //loads data and populates Model
$model->setBar('bar');
$data->save(); //reads data from Model and saves
}
Controller mediates between Model and Datastore
Seems a bit verbose and requires the model to know that a datastore exists.
//controller
public function update()
{
$model = $this->loadModel('foo');
$data = $this->loadDataStore('foo');
$model->setDataStore($data);
$model->getDataStore->loadBar(9); //loads data and populates Model
$model->setBar('bar');
$model->getDataStore->save(); //reads data from Model and saves
}
Datastore extends Model
What happens if we want to save a Model extending a database datastore to a flatfile datastore?
//controller
public function update()
{
$model = $this->loadHybrid('foo'); //get_class == Datastore_Database
$model->loadBar(9); //loads data and populates
$model->setBar('bar');
$model->save(); //saves
}
Model extends datastore
This allows for Model portability, but it seems wrong to extend like this. Further, the datastore cannot make use of any of the Model's methods.
//controller extends model
public function update()
{
$model = $this->loadHybrid('foo'); //get_class == Model
$model->loadBar(9); //loads data and populates
$model->setBar('bar');
$model->save(); //saves
}
EDIT: Model communicates with DAO
//model
public function __construct($dao)
{
$this->dao = $dao;
}
//model
public function setBar($bar)
{
//a bunch of business logic goes here
$this->dao->setBar($bar);
}
//controller
public function update()
{
$model = $this->loadModel('foo');
$model->setBar('baz');
$model->save();
}
Any input on the "best" option - or alternative - is most appreciated.
© Stack Overflow or respective owner