I’m about to do a PHP website using the MVC pattern. I am not using a framework as the site is fairly simple and I feel that this will give me a good opportunity to learn about the pattern directly. I have a couple questions.
Question 1: How should I organize my views? I’m thinking of having a Page view which will have the header and footer, and which will allow for a Content view to be nested between them.
Question 2: If I have 5 Content pages, should I make 5 different views that can be used as the content that is nested within the Page view? Or, should I make them all extend an abstract view called AbstractContent?
Question 3: What about controllers? I think there should be one main controller at least. But then where does the request go from there? To another controller? Or should I just call the Page view and leave it at that? I thought that controllers were supposed to handle input, possibly modify a model, and select a view. But what if one of the views nested within the view that a controller calls requires additional input to be parsed?
Question 4: Are controllers allowed to pass parameters into the view? Or should the controller simply modify the model, which will then affect the view? Or is the model only for DB access and other such things?
1 – This is a matter of preference. The simplest way would be to have a separate header and footer file. Then you could do something like this in your page controller
If you were to go the nested route you would have to start fiddling with str_replace and that starts heading towards a template engine, out of scope for this answer.
2 – No need to make views objects. A “view” can just be a file on your filesytem that contains the html for that view. Like my example above. These pages can contain basic php to loop/echo variables as well.
3 – You are describing a front controller (sometimes called dispatcher or router). This is really the way to go. There are a couple methods for creating a front controller.
You can have an array of urls that point to controllers.
or you can use the first “directory” in the url as the controller name and load that file form your controller directory.
4 – The entire point of the controller is to get info from the model and pass the data to the view.
Edited for comment
If you want a bunch of views to have a sidebar you just include that view in the other view. For example:
Just make sure that in controllers that “control” pages with sidebars you include some code for sidebar functions:
$sidebar_search_resultscould be an array of results that your sidebar view parses and displays.