Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is the best practice for adding persistence to an MVC model?
    text
    copied!<p>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.</p> <hr> <h3>Datastore interacts with Model</h3> <pre><code>//controller public function update() { $model = $this-&gt;loadModel('foo'); $data = $this-&gt;loadDataStore('foo', $model); $data-&gt;loadBar(9); //loads data and populates Model $model-&gt;setBar('bar'); $data-&gt;save(); //reads data from Model and saves } </code></pre> <h3>Controller mediates between Model and Datastore</h3> <p>Seems a bit verbose and requires the model to know that a datastore exists.</p> <pre><code>//controller public function update() { $model = $this-&gt;loadModel('foo'); $data = $this-&gt;loadDataStore('foo'); $model-&gt;setDataStore($data); $model-&gt;getDataStore-&gt;loadBar(9); //loads data and populates Model $model-&gt;setBar('bar'); $model-&gt;getDataStore-&gt;save(); //reads data from Model and saves } </code></pre> <h3>Datastore extends Model</h3> <p>What happens if we want to save a Model extending a database datastore to a flatfile datastore?</p> <pre><code>//controller public function update() { $model = $this-&gt;loadHybrid('foo'); //get_class == Datastore_Database $model-&gt;loadBar(9); //loads data and populates $model-&gt;setBar('bar'); $model-&gt;save(); //saves } </code></pre> <h3>Model extends datastore</h3> <p>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.</p> <pre><code>//controller extends model public function update() { $model = $this-&gt;loadHybrid('foo'); //get_class == Model $model-&gt;loadBar(9); //loads data and populates $model-&gt;setBar('bar'); $model-&gt;save(); //saves } </code></pre> <h3>EDIT: Model communicates with DAO</h3> <pre><code>//model public function __construct($dao) { $this-&gt;dao = $dao; } //model public function setBar($bar) { //a bunch of business logic goes here $this-&gt;dao-&gt;setBar($bar); } //controller public function update() { $model = $this-&gt;loadModel('foo'); $model-&gt;setBar('baz'); $model-&gt;save(); } </code></pre> <hr> <p>Any input on the "best" option - or alternative - is most appreciated.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload