I have some code where Controller
depends on the Model
, and in my case Model
acts like a Database Access Object.
use FQDN\Model;
class Controller
{
/** @var FQDN\Model */
private $model;
function setModel(Model $model)
{
$this->model = $model;
}
function showPage()
{
// model is set up (injected) in constructor
$data = $this->model->getData();
return ViewModel($data);
}
}
At first, in previous code iterations, my Model
was NOT injected into my Controller
and I was told that I should not just inject the Model
as I did above, but do inversion of control to the point where Controller
does not depend on Model
at all. Like so:
class Controller
{
/** @var array */
private $data; //controller-specific data
function setData(array $data)
{
$this->data = $data;
}
function showPage()
{
// data has already been injected into controller
// Controller has been created via Factory Method
// and populated with data
return ViewModel($this->data);
}
}
Controller is NOT aware of the model. Model
is outside of Controller
entirely. ControllerFactory
(or ControllerBuilder
) will instead:
- create the Controller
- invoke the
Model
- populate Controller with controller-specific data
I wanted to ask if there is a clear guideline for MVC that I should follow as far as having Controller depending on the Model, or having it specifically NOT depending on the model at all. Because even with dependency injection, my first code example still has code constructs inside Controller that make it aware of the model and hence dependent on it. I do not konw
Degrees of Separation
If you will I can define some degrees of separation from tighter coupling to looser coupling:
- Model is instantiated inside the Controller (hardwired)
- Model is injected inside the Controller via constructor or a setter (injected)
- Model is instantiated inside the ControllerFactory, data extracted from the Model and passed into Controller (separated)
All will "work" but what can help me decide which one is best for which particular case. Or is there a clear guideline for this?
Model
is kind of like a service layer in my first example. Yes? I considered it as a Service because of the way it is called like$data = $this->model->getData()
. I can call it a Service instead. Call it a "data service". I mean I can have several different services but my question remains ... if I call a "Model" a "Service". I mean what would be the difference? – Dennis Feb 26 '16 at 18:37Service
layer? Or are you suggesting that I should keepService
,Model
,Controller
independent of each other? My question is, no matter how many layers are introduced, how do I 'connect them' to each other? Do I use dependency injection (which still keeps the dependency), do I keep them completely separate of each other, or is it really 'up to me'? – Dennis Feb 26 '16 at 20:32