I have a simple PHP MVC framework that works this way:
StaticFramework (1)
|
V
DIC (2)
|
V
HTTPRequest
|
V
App <-> Router
|
V
Controller <-> Model
|
V
View
|
V
HTTPResponse
(1) StaticFramework
is a static "Front controller" that gives the App
its default dependecies with the (2) DIC
(Dependency Injection Container), which works in a similar way to Pimple. The container can be accessed to change those default dependecies. For example, the Router
class is injected in the App
by the DIC
.
I have a problem here, as it is a MVC application, I have 3 important layers:
- Model;
- View;
- Controller.
Injecting the View
is easy as it is only a class which has a render
method that renders a PHP or HTML file, so I just have to inject one instance of View
in my Controller
.
But injecting the Model
in the Controller
seems harder. Each Model
is a separate class and so I can't inject it as I do for the View
. Each Model
might also require other dependecies, such as a Database
or a XML
class for example.
Moreover, I cannot predict which models the Controller
will require, as it might need several of them, for example, the ArticleController
requires the ArticleModel
and the UsersModel
.
I have a few solutions:
- Injecting a
ModelFactory
class in theController
which will instanciate the models for theController
. But as eachModel
might require different dependencies, theModelFactory
must know which one it will need, which doesn't seem possible with aDIC
similar to Pimple; - Not injecting models in the
Controller
, and leaving each of them as a separate class, that extends what they need. For exemple, aModel
should extendDatabase
if it requires a MySQL connection. But it means the model is tightly dependent of its parent, and it makes it impossible for aModel
to use mock classes or have several data sources, for example, what if aModel
needs bothDatabase
andXML
?
So, what is the best way to inject models in the Controller
in the case of my framework?
Thank you in advance for your answers.