In my application I have one View
object which can load($template)
a template to get it ready to be rendered using the render()
method.
In all the stuff I have read about Views
sometimes I see people doing it the way I currently do it and other times I see people doing something like the following
class ProductView extends View {
}
class CheckoutView extends View {
}
Having a separate View
per page.
What are the advantages/disadvantages of both ways?
Any advice would be great thanks.
View should not be "loading templates". If you have code like
$this->load('header');
in the view, then it is a violation of SRP. View (sometimes) uses templates to create a response for the user, but it should not be creating them.
In the most of the articles that you will encounter about view, you will read about the interpretation of view from Rails (ands its clones). In RoR you do not have view. Only a glorified dumb template.
The structure of presentation layer makes it preferable for you to have 1:1 relation between controllers and view. Each view becomes responsible for handing of the response that has been triggered by user's input. Therefore: you page would usually have a one view per execution time.
In more complex cases you might want to look into concept of composite view. This approach lets you separate the the presentation logic in smaller chunks. This also makes it much easier to structure your code, if you user ViewModel.
The bottom line is this: if you have one view per whole application, then you are doing it wrong.
The one view-per-page is definitely most suitable for the web. Watch out that I didn't mean one view-per-controller but per different page. You want to have different templates that can be called by different views (such as the header, the footer or the navigation bar).
For example inside BlogPostView
you would have:
$this->load('header');
$this->load('post', $data);
$this->load('footer');
and then render it with:
$this->render();
It has no "the only true solution". But as for me, View must be as simple as possible. Like printf function. Do you want to extend printf behaviour? I think no!