MVC in Web apps?

maw

Supreme [H]ardness
Joined
Sep 27, 2000
Messages
4,135
I'm trying to wrap my head around the whole concept of MVC in developing PHP web applications. I sort of understand the general ideas, but for the life of me I just cannot translate that to any of the real world stuff I do.

I mostly build small, one-off applications at work (phone books, surveys, event registrations, etc.) basically the "enter stuff in a DB on one end and display a search-able, sortable formatted page for the users" on the other end. Trying to apply MVC concepts to these kinds of applications seems to me a huge time sink for very little gain. I feel like I'm writing 2-3 times as much code building classes for models, views and controllers in addition to templates for the one or two pages that a small project usually needs.

I usually get frustrated and simply resort back to the old approach of DB query code on top of the page and some interleaved or included PHP code in the <body> for display.

Am I somehow unclear on the concept here when it comes to MVC? Or am I simply not building the types of web apps that would require MVC?

Any input or suggestions would be greatly appreciated. I'm starting to feel like I'm the only person that doesn't "get it" right now.
 
There's no point in making something more complex just because somebody says it's the "right way" of doing it. If you app consists of a form, a list & a display that all work with a single data type, you're probably not gaining too much from MVC. If your app has dozens of screens, with a user system, shared page layouts & complex business logic that needs to be shared between pages, you're more likely to see the advantages.

Even without a full-blown MVC, you might benefit from using a framework to simplify form building/validation and CRUD operations - I seem to remember CakePHP being able to build scaffolding to handle the sorts of cases you describe.
 
I find it similar to HTML (maybe... controller?) and CSS (view) and Javascript (logic). Sure, you can have one huge HTML page with inline CSS and Javascript, but if you try to go back and change a word, you have to look through so much code to find that word. Or if you wanted to change the color of the background... you'd have to revisit each page and change the CSS for each instance.

For one, MVCs make things more organized and encapsulated. You keep templates (view) separate from logic (model) separate from how it got there (controller). So when you develop the logic, you don't care about how the app decides to run that piece of logic. When you develop the templates, you don't care of how the data got there. And with that, when you want to change a little bit of logic, you don't have to look through HTML, and likewise for templates, you don't have to look through PHP (or any other language).

Another thing is that MVCs excel at code reuse.

If your phonebooks, surveys, and event registrations all required the same database connection, instead of establishing a connection for each page, an MVC would establish it automagically. You wouldn't have to worry about establishing a database connection ever again in your app. And if you ever wanted to change your database connection information, you change one line.

If your applications required user authentication, your controller can handle it and encapsulate it from the rest of your program.

If your MVC required the same form validation (preventing SQL injections, rejecting tags), you can make it do it automagically.

And something awesome about MVCs is it's view. You can go from HTML to PDF to JSON to any other sort of view and not worry about the logic at all.

I use to think MVCs were worthless. I thought they had unnecessary overhead and made coding applications more of a headache than they should be (worked with component design in Joomla for work [MVC] and then random projects on the side [not MVC]). Then I noticed I was copying and pasting a lot of code between files and an MVC started to make a lot of sense!
 
Thanks johnglenn,
your explanation went a long way in clarifying things more for me. If what I understand from your post is correct, it looks like I've been doing some crude version of MVC without realizing it. E.g. I have a DB connect class that I use in all my apps that abstracts out all the server connection info and query functions. For each application I extend this class to add the CRUD logic for that particular app.
I also like to code all my PHP processing logic (query building, sorting, organizing, searching, etc) on it's own page and then including the output on an HTML page instead of doing it all on one page.

My pages tend to have this structure:
Code:
<?php
include("processQuery.php);//process form input, generates result set, and writes it to the variable $queryResults
?>
<html>
.
.
<body>
<form.....>
</form>
<?php echo($queryResults)?>
</body>

..am I going in the right direction here?
 
if you are writing 2 to 3 times more code in MCV then you are prob not doing the correct way. MCV will modularize everything and a good framework will have components libraries for you to do everyday stuff.
Model is like your data class, a simple model will only have 5 loc, and is backed by database which will be connected already as long as you configure your framework correctly. You don't need to write you query class, that to me already saves you a lot of coding.
control basically just controls your data and how you want it, then it spit that to view to be displayed.

I strongly recommend you to read the cakephp doc, I must tell you that MCV have a very steep learning curve that's why it seems useless at first. Take a full day just ready everything on http://book.cakephp.org/
you will see how it works and if you like to use it for your projects.

an example for you, how long would it take you literally from zero to write a site that has contents in database(include database setup, query and everything), registration system, an authentication system that depend on your specification certain function requires login and allow you to edit, delete contents?
I can tell you from scratch, with nothing in my database, not even tables, and no framework installed to what I just said in less than 20mins. so the 20 mins include installations and database table creations. Where in traditional plain php will take me maybe 2 hours. I have to write different query functions and output and registration, and proper session handling, you should know 2 hours is understating if you want to do it right.
 
if you are writing 2 to 3 times more code in MCV then you are prob not doing the correct way. MCV will modularize everything and a good framework will have components libraries for you to do everyday stuff.
Model is like your data class, a simple model will only have 5 loc, and is backed by database which will be connected already as long as you configure your framework correctly. You don't need to write you query class, that to me already saves you a lot of coding.
control basically just controls your data and how you want it, then it spit that to view to be displayed.

I strongly recommend you to read the cakephp doc, I must tell you that MCV have a very steep learning curve that's why it seems useless at first. Take a full day just ready everything on http://book.cakephp.org/
you will see how it works and if you like to use it for your projects.

an example for you, how long would it take you literally from zero to write a site that has contents in database(include database setup, query and everything), registration system, an authentication system that depend on your specification certain function requires login and allow you to edit, delete contents?
I can tell you from scratch, with nothing in my database, not even tables, and no framework installed to what I just said in less than 20mins. so the 20 mins include installations and database table creations. Where in traditional plain php will take me maybe 2 hours. I have to write different query functions and output and registration, and proper session handling, you should know 2 hours is understating if you want to do it right.

Saving time does NOT make it a better solution.
 
Saving time does NOT make it a better solution.

But a well-written MVC saves time in the long run and is a great solution, especially in larger applications. In smaller websites, it might not be the best solution, but it's not a bad one.

The 2 "best" CMSes for larger sites, Joomla and Drupal, are based on MVC. I don't know if you could find many webapps that are not based on the MVC.

Digg's lead architect, Joe Stump, wrote an article about MVCs and how he created one to use for Digg (or digg's is based off of it). That's how I first got into it. It blew my mind in that I had no idea what was going on. I must've read that thing 20 times by now.
 
Saving time does NOT make it a better solution.

I never said saving time makes it a better solution. The op was asking about MCV and how come he is writing 2 to 3 times MORE code, which I then explained why he is doing it wrong by providing an example that it is actually much much less code to write. and point him to read more on the MCV framework by looking at one of the framework "cakephp" as I think it has good information on their documentation since the whole point of this thread is him asking about MCV. Actually reading some's reply and realizing the reply is in regard to the original poster's question but not as a general statement might be hard, but try that once in a while.

If you are a developer worth your salt, you will choose the right tool for the project, not by sticking to one method or framework, you use what is available. For small project MCV is perfectly fine, for larger project MCV might/might not be the right tool depend on your server environment, since MCV can scale out. I can tell you right now that cake php is slow for any high traffic website unless you are scaling the MCV out. I have never said anything about the framework being "better."

Just so you know, the whole point of using ANY framework is so that developer can actually concentrate on making the content better not on writing the same code over and over.
 
OK, so here's my other question. Once you "get" the idea of an MVC framework, could the concepts be easily applied to any framework? Or are frameworks so unique that each requires weeks of studying to get up to speed with it?

Right now I find learning something like Cake quite daunting, and one of my biggest concerns is that years from now, maybe after Cake version x.xx is no longer supported or I moved on to another framework, how easy would it be to revisit that code to make modifications?

I've had to update some pretty old PHP code recently, and while the coding style makes you shake your head sometimes, it's still very easy to follow what's going on. I just don't want to be in a situation where I'd have to spend weeks re-learning an ancient framework in order to make simple modifications later down the road.
 
Try this tutorial http://www.killerphp.com/tutorials/object-oriented-php

The videos (bottom of the page) would be a good place to start. Then follow the text based tutorial when you're done.

Thanks for that link.
Actually, everything he suggests in those videos pretty much sums up how I currently write code (data connection class, data formatting class, view page that uses includes to embed the output from the formatting class). I guess that's reassuring.
 
OK, so here's my other question. Once you "get" the idea of an MVC framework, could the concepts be easily applied to any framework? Or are frameworks so unique that each requires weeks of studying to get up to speed with it?

Right now I find learning something like Cake quite daunting, and one of my biggest concerns is that years from now, maybe after Cake version x.xx is no longer supported or I moved on to another framework, how easy would it be to revisit that code to make modifications?

I've had to update some pretty old PHP code recently, and while the coding style makes you shake your head sometimes, it's still very easy to follow what's going on. I just don't want to be in a situation where I'd have to spend weeks re-learning an ancient framework in order to make simple modifications later down the road.

MVC does have a steep learning curve, but once you know it, they are pretty much the same across frameworks. For example, cakephp is much more MVC than codeigniter, if you know how to use cakephp, you will be able to pick up codeigniter in hours if not less. It's then more about learning the framework specifics. It's one of the reasons why I pointed you to cake instead of CI, because Cake takes MVC and modularization a step further. You can not have your app without the model, but I believe CI allows you to not have a model. In CI, you have to write your own model queries, but in cake, it's all taken care of. I think in general, if you are writing more code using any framework, you are prob doing something wrong, because the very nature of a framework. (I personally prefer CI, but to learn MVC, I think cake is better to read cuz the doc pages are easier to follow, CI pages you have to drop down the menu and select what you want to read.)

If you are worried about deprecation, in my opinion, if I care about a site, I would always update it to the latest version, often that would require little modifications. Of course if you switch framework completely, you might have to rewrite a lot of stuff just to fit the framework. To me, once I have an outline of what the app is, coding is always the easiest part.

someone once said, you should always pick up a book after another about something that will help your trait. I think it would be a nice addition to learn about MVC not because you need it, but it adds something to your belt. Many major websites deploy the MVC architect.

If you are serious or interested in web design(if you are posting under this sub forum, you are either one or both) you naturally would keep learning new stuff as it is either necessary or are just fun to you. When I learned MVC, it was more like fun to me, I spent 2 full days going over and over the documentations. If you don't already know, after you learn about the MVC, I think picking up flex is another good choice.

because we all know, in real life, more often than we like, you don't get to choose what you want to use, you do what you are told to use, unless you are just doing your own projects. I know it's a lot of rambling, but I am just typing out what is immediately comes to mind, I hope this helps to encourage you to learn something even though it is not necessary.
 
On a related topic about possible overhead with OOP. I don't know if there's really that much overhead. Sure if you use a fully developed framework with a ton of junk you don't need it might be slower but check this out...

I'm running Aptana (web dev IDE that has a self contained PHP server/debugger) on a C2D e6420 with 2GB of ram.

I created a validation class then created another class that extends the validation class.

The base validation class has a few methods. Mostly generic stuff that would be useful in any type of validation class.

Examples:
Check if a value has at least x chars but not more than y chars.
Check if a value is anything but 0-9.
Check if a value is a legit float.
Check if an email address matches a "multi language acceptable" pattern using preg_match.
Convert a value to a 99.9% safe sql value.

Then in the extended class I have 22 more methods that are specific to the project I'm working on.

So imagine this...
$validate = new validate_ext();
$f_email = $validate->email("[email protected]");

Except with 22 variables being created, validated, then echo'd out.

Anyways I ran a microtime() before I created the class objects and then after I echo'd everything out and the end result is always about 0.000519. For the amount being processed that seems pretty reasonable (I'm throwing around quite a few variables, doing a fair bit of logic and in 3 cases I'm passing a 3-18 element array).

Without classes it would be slightly less time (no question about it) but if you're talking about a few milliseconds I don't think it matters in the end. It's just not an even trade off.

Btw the php manual says microtime() with the true param reports the value back in seconds. When comparing I did use true. Wouldn't this be 0.52 milliseconds then? Is it really possible that it's executing this fast?
 
I created a validation class then created another class that extends the validation class.

The base validation class has a few methods. Mostly generic stuff that would be useful in any type of validation class.

Examples:
Check if a value has at least x chars but not more than y chars.
Check if a value is anything but 0-9.
Check if a value is a legit float.
Check if an email address matches a "multi language acceptable" pattern using preg_match.
Convert a value to a 99.9% safe sql value.

Heh.. I wrote almost the EXACT same class a couple years ago and have been using it since. It started out as a collection of discreet functions until i rolled them all up into one class that I called Validator. So I have something like
Code:
$validate = new Validator();
$clean_text = $validate->sanitizeText($_POST['sometext'],150);//accept first 150 characters (this parameter is optional), and make SQL safe
$ID = $validate->validateInt($_POST['ID']); //check if ID is a valid number, return 0 if it is not.

Also, the more I'm reading about MVC, the more it's apparent that it's a pattern I've been following for the most part all along, I was just doing it using a mostly procedural instead of OOP approach. Now that I'm looking at it from a more OOP perspective, it's starting to make a lot more sense.
 
Back
Top