MVC vs Templating

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

MVC vs Templating

Post by alex.barylski »

So I'm really new to MVC, having very little interest in learning anything about it and being content with Smarty type template techniques. However I've decided there is no harm in learning something new, so I started reading up on MVC a little more, to gain more knowledge then just a basic conceptual understanding.

I now see it's analogous to MFC's Document/View architecture...well sorta' :)

Anyways...I have a few questions in regards to MVC most specifically when used in web development...

First off...I really like template approach...so why then would I switch to MVC?

Remember I have very little understanding of MVC and I've been using template style techniques in web development for the last 5-6 years...so pardon my being ignorant or stubborn to change :)

I get the paradigm concept...separate objects to deal with:

1) Controller - User input
2) View - Output
3) Model - Data

I get why each communicates (or doesn't communicate) with each other...but template frameworks accomplish much the same thing...

In Smarty for instance...I can have a single script which loads a (view-port) template based on user input...keeping all business logic inside this script, plus a pseudo controller (ie: Action Request Handler or whatever you might call it).

So business logic and controller (ARH) reside in the same script, the visual output is kept almost entirely separate. Tada...I've accomplished separation of Interface vs Implementation...

It's no secret HTML and code when mashed together makes for a hard to read program and messy as hell...it's like coding with GOTO :)

Anyways, to further strengthen my case...HTTP doesn't facilitate it self nicely to MVC IMHO. The reason being - the way user input is sent to the program.

I can emulate a MVC approach by doing what I said above...having the business logic stored in a /scripts/ directory and invocation of that action/business logic script done implicitly via HTML FORM's action attribute...

This way, most business logic (adding, removing, updating members, etc...) can be stored in small nicely written scripts which do nothing more than Update, Delete, Create...and then redirect back to the index.php to regenerate the viewport...

index.php is responsible for generating a display by selecting a template based on user's request...

So I guess what i'm asking is given what i've described above...how would a MVC framework like Mojavi be any better???

From what i can tell - I have basically achieved MVC using not a PHP library (I actually don't use smarty - but bTemplate for speed and flexibility) other then a templating engine.

1) index.php is the viewport - selecting templates
2) HTML intrinsically handles business logic invocation via FORM action attribute

The model doesn't really exist in my proposed approach...seeing how each script (Update, Create, Delete, etc...) would likely just require knowledge of the same SQL table and perform a direct SQL call.

But I am quite OK with that...cuz this far over the years this technique has served me well...but regardless I"m curious...

1) Can someone explain how MVC would make my job easier when dealing with a Member (update, delete, create, etc...) type application???

2) How does MVC support a model when dealing with a SQL table???

I"m not sure if I've made complete sense...it's 12:11 here and I have to be up at 6 :(

But if you can make half fast sense of what i'm asking and can answer me or at least offer me suggestions or comments...please do :)

Cheers :)
User avatar
Maugrim_The_Reaper
DevNet Master
Posts: 2704
Joined: Tue Nov 02, 2004 5:43 am
Location: Ireland

Post by Maugrim_The_Reaper »

I'm not a complete MVC expert (at least in the strictest sense).

Templating by itself does not necessarily accomplish the full MVC separation. For example, if your business logic is directly calling Smarty->assign() you have not separated Business Logic from the View. To explain - what if I wanted XML output, or plain text output instead?

Generally I (being not a strict MVC expert) would use create a ViewData object. My business logic would set up this data but NOT call a specific view strategy. Rather the Input Controller (Front or Application Controller) would determine what View should be used - the View would determine my output strategy , e.g. Smarty, XML, Plain Text. Based on this "strategy" it would create a View Helper - say ViewHelper_Smarty for example.

Into the ViewHelper it would pass the ViewData object - basically Smarty would be instantiated, assigned the data from ViewData and the template fetch()'d. The output (the fetched parsed template) would be pushed into a Response object which the Controller can use to call its output() method.

If you can actually follow that you'll notice the differences. Business Logic generates Variables. Variables are passed to a View. The View passed Variables to a Helper (can be several). The Helper generated Output. Output is echoed, or made to echo, from the Controller.

It's interesting to note that the ideal is to separate Business Logic from Presentation Logic - key here is Logic, not PHP/HTML. If you have logic in your Business Logic determining what will be output that is still Presentation Logic. MVC sort of formalises concept by referring to Views - which actually are PHP - just PHP that handles Presentation Logic.

Using Smarty gets you there to an extent, but restricts you to HTML/XML. You can also note that Smarty still mixes logic with HTML (unavaoidable for templating) so keep in mind PHP can be validly mixed with HTML without a new sub-language....;) Also you have just hardcoded a dependency on Smarty (unless Smarty is created and passed in from outside). You're also tying View and Command in a one to one relationship - unless accompanied by some sort if switch/if...else construct - even though a Command (a single group of Business Logic) may map to several Views depending on circumstances.

This might be clearer:

Controller: User Input, Centralised Tasks, Output
Model: Business Logic, Data Manipulation
Data Access: Data Read, Write, Update, Delete, etc.
View: Presentation Logic, Content Generation

I added Data Access since it is an extra layer MVC won't mention (usually grouped with Model, though its far more useful to view them as separate layers). This can easily differ between developers - so expect a few alternate takes following my post ;) Just to note that Content Generation and Output are in two different layers - so using Smarty->display() actually breaks yet another MVC layering method.

It is by the way entirely valid to merge View and Model - MVC comes in two flavours. Model 1 and Model 2. Model 2 is the stricter separation of Views from everything else. Depends on the MVC model you choose.
RobertPaul
Forum Contributor
Posts: 122
Joined: Sun Sep 18, 2005 8:54 pm
Location: OCNY

Post by RobertPaul »

If you can actually follow that you'll notice the differences. Business Logic generates Variables. Variables are passed to a View. The View passed Variables to a Helper (can be several). The Helper generated Output. Output is echoed, or made to echo, from the Controller.
Well, I gotta say ... I've been trying to wrap my head around MVC for a bit, and for what it's worth that's the simplest and clearest explaination I've seen yet.
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Post by alex.barylski »

Maugrim_The_Reaper wrote:I'm not a complete MVC expert (at least in the strictest sense).

Templating by itself does not necessarily accomplish the full MVC separation. For example, if your business logic is directly calling Smarty->assign() you have not separated Business Logic from the View. To explain - what if I wanted XML output, or plain text output instead?

Generally I (being not a strict MVC expert) would use create a ViewData object. My business logic would set up this data but NOT call a specific view strategy. Rather the Input Controller (Front or Application Controller) would determine what View should be used - the View would determine my output strategy , e.g. Smarty, XML, Plain Text. Based on this "strategy" it would create a View Helper - say ViewHelper_Smarty for example.

Into the ViewHelper it would pass the ViewData object - basically Smarty would be instantiated, assigned the data from ViewData and the template fetch()'d. The output (the fetched parsed template) would be pushed into a Response object which the Controller can use to call its output() method.

If you can actually follow that you'll notice the differences. Business Logic generates Variables. Variables are passed to a View. The View passed Variables to a Helper (can be several). The Helper generated Output. Output is echoed, or made to echo, from the Controller.

It's interesting to note that the ideal is to separate Business Logic from Presentation Logic - key here is Logic, not PHP/HTML. If you have logic in your Business Logic determining what will be output that is still Presentation Logic. MVC sort of formalises concept by referring to Views - which actually are PHP - just PHP that handles Presentation Logic.

Using Smarty gets you there to an extent, but restricts you to HTML/XML. You can also note that Smarty still mixes logic with HTML (unavaoidable for templating) so keep in mind PHP can be validly mixed with HTML without a new sub-language....;) Also you have just hardcoded a dependency on Smarty (unless Smarty is created and passed in from outside). You're also tying View and Command in a one to one relationship - unless accompanied by some sort if switch/if...else construct - even though a Command (a single group of Business Logic) may map to several Views depending on circumstances.

This might be clearer:

Controller: User Input, Centralised Tasks, Output
Model: Business Logic, Data Manipulation
Data Access: Data Read, Write, Update, Delete, etc.
View: Presentation Logic, Content Generation

I added Data Access since it is an extra layer MVC won't mention (usually grouped with Model, though its far more useful to view them as separate layers). This can easily differ between developers - so expect a few alternate takes following my post ;) Just to note that Content Generation and Output are in two different layers - so using Smarty->display() actually breaks yet another MVC layering method.

It is by the way entirely valid to merge View and Model - MVC comes in two flavours. Model 1 and Model 2. Model 2 is the stricter separation of Views from everything else. Depends on the MVC model you choose.
Ok, I have read your post twice and I can't say you've convinced me to switch to MVC as opposed to using templating systems...I guess I still don't see the light :oops:

Templating, does as you agreed...seperates presentation from business logic...

MVC by the sounds of it, simply adds another "layer" to handle requests/user input...

Like I said, HTML/HTTP by design, handle action requests for me via the FORM action attribute...so I don't really have a need to have a seperate object intercept mouse clicks, etc...

Here...I'll ask specific questions instead:

1) Why would I need a controller when AFAIK HTML has built in support via FORM action attribute...what am I missing about controllers? what benefit does it offer?

2) Does a View then use smarty to ouput or is output hardcoded as HTML strings via echo??? What benefit does a view have over templating???

Thanx for the input,
Cheers :)
User avatar
Buddha443556
Forum Regular
Posts: 873
Joined: Fri Mar 19, 2004 1:51 pm

Post by Buddha443556 »

Ok, I have read your post twice and I can't say you've convinced me to switch to MVC as opposed to using templating systems...I guess I still don't see the light
If whatever you're doing in PHP works for you, such as templates, then why switch? MVC is a way to modularizing an application to allow for easy maintenance of it's individual parts. While understanding how MVC accomplishes this feat may help your programming there's no requirement to use MVC. MVC after all is said and done is just a pattern. Something used to solve a particularly common problem. It's certainly a pattern worth studying though, maybe there's more to learn?
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post by Ambush Commander »

Err... Forgive me if I'm wrong but according to PoEAA, MVC is not exclusive from Template View... In fact, template view is the V in MVC.

The thing is, Fowler argues, Templating systems don't do a good job of seperating the Model from the View (especially the hodgepodge of ifs and elses and the rest of the programming language you end up needing).
User avatar
Maugrim_The_Reaper
DevNet Master
Posts: 2704
Joined: Tue Nov 02, 2004 5:43 am
Location: Ireland

Post by Maugrim_The_Reaper »

The problem I've noted with MVC is not that the pattern is complex - its that folk seem to inevitably add to the list of requirements and literally make it more complicated. If I've said it once, I've said it a thousand times - you don't need a framework to use MVC. I can hack together an entirely valid MVC setup in a few days. It's a pattern - not a concrete code requirement.

I also like to state that developers develop code, and patterns should not develop anything besides inspiration and understanding.

Take the two above and I'm not convincing anyone to use MVC. It's a powerful pattern for modularising re-usable components. It's so reusable that after you invest the up front effort an application task should be pretty small compared to what you probably now use. The rest of the code would be tied up in specialised classes in the View, Data Access and Model layers.

The issue is that up front time you invested.

It might be your application is simple enough that the benefits from MVC are small. Even negligible. It does however make a lot of sense if you plan on expanding your application to a large degree in the future. I suppose one example is the common PHP application with templating.

Maybe you have a dozen PHP pagefiles - each uses templates so PHP/HTML are separated...sort of. Presentation Logic will still be in the files of course, since they'll need to make calls to Smarty, and decide which template to call. The rest of the code is where it gets interesting. Maybe you have a few SQL queries in the files. A few basic data operations. Some common control logic at the start of each file.

Its a dozen files - so maintenance is pretty simple and MVC is making little sense.

One day you wind up with a 50 pages. Now you have issues. Might have issues. The problem is if each page is duplicating certain blocks of functionality. It might be duplicated SQL queries, maybe a block of business logic is the same on several pages, or maybe you're doing very similar things with Database data (usually save, read, update, deletes).

With 12 pages it was maintainable, with 50 you have duplicated code. A bug anywhere might exist in similar blocks of code in a dozen other files - because they're all duplicated.

Now expand to a 100 pages. At this point you will have serious maintenance problems. It might even start you on the dangerous road of spending more time maintaining than developing.

You know, even at this point I'm not really convincing. The can avoid the above in other ways without using MVC. But here's the catch. MVC has 4 components - Model, View, Controller, Data Access. MVC in its entirety might be complex - but each layer in isolation forms its own distinct pattern. To be honest even a passing knowledge of ONE of those layers will help your design.

In short whether you use MVC or not - at least examine it. There may be a few pieces you can adapt to solve other problems without eating the whole cake. ;) That's the real fun part when you start looking at design patterns - they make solutions to many problems obvious.

I'll also drop a warning. Patterns like MVC are very simple concepts - and I mean really really really simple concepts. See RobertPauls response. The problem I've seen (I might get flamed for this) is a persistent need for some PHP developers to take a simple concept and complicate it to death. I use the term "Purists" to describe such developers since they allow the pattern to control development, rather than the developers having control. It's like speaking to robots - they will insist on the one true path to enlightenment and ignore the other dozen sitting in plain view.

After all this rambling... Its your choice. MVC is huge help (one of several) for applications that are growing beyond a few dozen pages. Its helpful because it separates all the components, removes duplications, and ensures that if you find a bug - you probably won't see it duplicated in a dozen other files. It results in many more classes - but often the smaller classes are focused and a lot simpler. Even if you decide against MVC - examine it anyways. Even the individual components might prove oddly useful without a full blown MVC implementation.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post by Christopher »

Hockey wrote:Here...I'll ask specific questions instead:

1) Why would I need a controller when AFAIK HTML has built in support via FORM action attribute...what am I missing about controllers? what benefit does it offer?
First, you have a Controller in your code right now, it's just mixed in or small. If you pull out the template code and the database calls there there will be some code left to connect things together -- that's the Controller. MVC just formalizes the dependencies.
Hockey wrote:2) Does a View then use smarty to ouput or is output hardcoded as HTML strings via echo??? What benefit does a view have over templating???
The View is just that part of the code that specifially generates the Response back to the browser. It can contain a template system or PHP generating HTML or just HTML from a file or something else or a mix of things. Again, your code right now has a View which in you case is the calls to Smarty plus the code that manages Smarty and then echos the output. So a template system can be part of the View, but they are not the same.

The bottom line is that you will know when you need MVC because you will have problems that your current code does not do very good solving. Typically that is when complexity increases.
User avatar
Maugrim_The_Reaper
DevNet Master
Posts: 2704
Joined: Tue Nov 02, 2004 5:43 am
Location: Ireland

Post by Maugrim_The_Reaper »

1) Why would I need a controller when AFAIK HTML has built in support via FORM action attribute...what am I missing about controllers? what benefit does it offer?
You still use the form attribute...;) Look at it this way - a controller becomes a single point where all requests will enter your application, and from which all responses will exit.

It enables a centralised control point. Think of all the stuff you need on every single page - you could centralise all that very easily, reduce duplication (if any) and ensure it is actually all being done for every single page request (since requests all go through the same point).
2) Does a View then use smarty to ouput or is output hardcoded as HTML strings via echo??? What benefit does a view have over templating???
Views are simply formalised presentation logic - maintained distinct from your business logic. All the business logic does is create relevent data for the view - it in itself makes no calls to Smarty or anything else.

It's benefit is that your View (whether smarty or not) is now maintained in independent separate classes. It makes a quick migration to an alternative (for example, Savant 2) a lot simpler. The idea of all this is to make maintenance and future changes as simple as possible. See my earlier description of how my own idea of a View works - there are a few ways, probably as many as there are developers.

They all boil down to separating Business Logic from Presentation Logic - from another direction, I'm basically saying your Business Logic shouldn't know nor care about what templating engine or other we're using this week - its independent.

MVC is one method of getting that independence. To give a more reasonable explanation - I develop PHP games as a hobby. MVC allows me to re-use 60% of the PHP code from one game to another. That's a big benefit. It's better also because I maintain that 60% as a separate project - so any changes are immediately applied to all my game projects simply by dropping in a new copy of the re-used code.
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post by Jenk »

From what I understand, a simple example of a controller is a site that uses index.php to include the content, rather than have a different addresses for each page.

e.g.:
index.php:

Code: Select all

<?php

$pages = array('main', 'register', 'foo', 'bar');

if (array_key_exists($_GET['pageid'], $pages)) {
    include($pages[$_GET['pageid']] . 'php');
} else {
    include('default.php');
}
?>
Thus index.php is the only page that is requested by the user agent, with the page id variable passed to it, e.g. http://www.somesite.com/index.php?pid=3

Instead of linking to http://www.somesite.com/bar.php

:)
alvinphp
Forum Contributor
Posts: 380
Joined: Wed Sep 21, 2005 11:47 am

Post by alvinphp »

MVC is a very general concept that spans well outside programming. To me, MVC stands for this in web programming:

M: Functions/Classes
V: Your HTML/Javascript/XML
C: The code used to determine what functions/methods to call.

And in web you also have what I call D which would be your Database. Stored Procs would fall under Model.

This is the structure I use for all web development where the 4 things above are seperated (as much as possible).
Last edited by alvinphp on Sat Oct 29, 2005 1:16 am, edited 1 time in total.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post by Christopher »

alvinphp wrote:MVC is a very general concept that spans well outside programming. To me, MVC stands for this in web programming:

M: Functions/Classes
V: Your HTML/Javascript/XML
C: The code used to determine what functions/methods to call.

And in web you also have what I call D which would be your Database. Stored Procs would fall under Model.

This is the structure I use for all web developmen where the 4 things above are seperated (as much as possible).
This defining goes on forever. I would say that the Model is not "Functions/Classes" but instead is the part of the program where the data or information is managed. The View often has code in it as well as HTML/Javascript/XML/etc.

One of the strange things about MVC is that it is supposedly two separations, not three. The first is the separation of the Model layer from the Presentation layer (View + Controller). The second separation is between the View (display code) and the Controller (program flow code). In MVC the Model has no dependencies on the View or Controller, and you try to minimize the dependencies of the View on the Controller.

The funny thing is that everyone's PHP scripts have Model, View and Controller parts. But usually they are interdependent on each other which can cause maintance problems as complexity increases. So MVC just adds the separations.
Post Reply