I’m playing with MVC in PHP. I’m not using a framework, I’m just trying to understand the pattern.
Sometimes I see controllers, for instance in this tutorial, that are instantiated with Models and Views passed into the constructor, and in the same tutorial the view ( here ‘Template’ ) class, takes a Controller in the constructor!
So my question is:
- Why might the view need a reference to its controller? Shouldn’t the view be the passive partner in this relationship?
- Should a controller ever have an internal reference to a particular model? Or to put it another way, why not just instantiate models in controller actions and use them that way?
If you have user inputs, you need to know where to send them.. to what controller.
I don’t like having my controllers play with models directly, because controllers are exposed to the “outside world”, and prone to attacks.
You can have a look at service layer pattern, Data Transfer Object pattern, etc.
I like to have my models isolated behind a service API that controllers will use.
If you need a good book about patterns, you can look for Martin Fowler’s 🙂