I'm developing a PHP MVC REST API which will have OAuth for authenticating if the call can be performed.
So my plan is to develop it for an Angular 2/4 app which will handle the API calls.
The idea was to create a structure where my domain for example test.com will have a subdomain api.test.com.And from it the API calls will be requested.
The thing that i would like to confirm before i start building this is my MVC backend structure.
Ref.Pic
Model will have all the logic
View will be the api.test.com/api/call presentation.Outputing the JSON in my case.
Controller will accept input exmp:the api.test.com/api/call call the logic in the Model if the call is correct.Than the call will react on the view where presenting the JSON.It would hold the OAuth also....
I'm trying to understand the whole concept of this, since i have tried several times to build it and every time i end up in a mess of code.I'd like to see if my understanding of the project above makes sense.
Thank you
There are multiple issues, that you will encounter as you try to apply SoC principle in your codebase.
And, what to do with communication between views and controllers, is one of the more visible ones. That's because, if you mess it up, there are no abstractions to hide it all behind.
The two major approaches are Supervising Controller and Autonomous View (which has no article, but you can deduce some of it from this and this).
Supervising controller
This approach is best suited for smaller applications (well .. for large values of "small", since really small projects don't really need the architectural bloat of MVC). It essentially looks like this:
/* in a controller */
public function verifyEmail(Request $request)
{
$identity = $this->search->findEmailIdentityByToken(
$request->get('token'),
Identity::ACTION_VERIFY
);
$this->registration->verifyEmailIdentity($identity);
$body = [
'status' => 'ok',
];
return new JsonResponse($body);
}
Essentially, what you have there is a controller, that interacts with the business model and (when necessary) populates the view with data. Then it causes the view to be rendered and returns the response.
In my own experience, I have found this to be the best approach to use, when writing backend applications, that are expected to only be manipulated via REST-like API.
As you see in the example, the "view" in this case is extremely trivial. It is basically array, that you render as JSON (which the provided code would actually do - it's copied from a real project).
Note:
If your intention is to fully implement REST as it was proposed (not just the REST-like resource endpoints) and/or
have functionality of resource expansion, then this approach might be wrong and even harmful.
Autonomous View
When your presentation logic becomes complicated or have to provide different UIs for the same application with the same functionality (like having single app with both website and REST API, with both xml an json interface), then using Supervising Controller becomes a ball and chain around your neck. Your controllers start to grow uncontrollably and your project can be described as "legacy codebase", before it even reaches production.
And that's where you use this approach.
You use views and controllers as completely separate classes and you interact of their instances at the same layer (for example: bootstrap stage). It ends up looking something like this:
/* in /src/application.bootstrap.php */
$command = $request->getMethod() . $parameters['action'];
$resource = $parameters['resource'];
$controller = $container->get("controllers.$resource");
if (method_exists($controller, $command)) {
$controller->{$command}($request);
}
$view = $container->get("views.$resource");
if (method_exists($view, $command)) {
$response = $view->{$command}($request);
$response->send();
}
Again, example from a different live project, which also uses a DI container. In this case there is only one UI (hence, no "type" prefix, when making a view instance), which mean that the code can take advantage of 1:1 relation between controllers views (it would be 1:n, if you need multiple UIs).
The controller in this case basically only "writes" to the model layer. And the view (which also has access to services from model layer) only performs "reads" and extracts only the information, that it requires for populating templates and rendering them.
And, if your presentation logic grows further, it is a good idea to start adding presentation objects, that will contain the repeating parts of the presentation logic (e.g. deciding, which menu item in the sidebar has to be expanded and which submenu item has to be highlighted), that are common for multiple views.
If your backend application only deals with API, then this approach might be too complex, unless you are doing one of the things mentioned in the "note" part.
... maybe this helps a bit
Yes, That makes sense. I suggest using the Laravel framework instead. Or the OctoberCMS even better.
Related
I'm a novice, but struggling hard to implement this interactive application I'm working on "the right way" or at least a good way in terms of scalability, maintainability, modularity, development speed and tool independence. That's why I chose the REST design guides and a framework which implements MVC.
However I can't get my head around where to put what in the following situation and any input or reading material from a more experienced developer in this techniques would be greatly appreciated :
I'm developing a single page web app which creates a resource that has several nested resources within. In the create methods and alike, I need to call the create methods from the nested resources. Right now every GET request is responded with a JSON, which the front end then parses, shows and add dynamically to the page accordingly. The question is : where should this create and store methods from nested resources be, in the controller or in the model?
Currently, my approach is : since the controller function is to handle user input, interact with model and return the view accordingly, the nested store methods are in the model since they're not created independently, their create methods are in the controller since they're requested from ajax calls, but this isn't nested, and so on. I'm worried that this is too mixed up and not general.
Am I ok ? Am I mixed up? I don't wanna make a mess for my coworkers to understand. Theory becomes tricky when applied..
I'm gonna have a go at this. I am myself still learning about this as well, so if any information is wrong, please correct me.
In terms of scalability, you should always be able to create any model independently, even though at this point it appears not strictly necessary. The REST paradigm stands for exactly this: Each model (a.k.a. resource) has its own (sub)set of CRUD endpoints, which a client application can use to perform any action, on any composition of data (compositions in which elementary entities are mostly the models you specify).
Furthermore, a model should be concerned with its own data only, and that data is typically found in a single table (in the case of relational datastores). In many cases models specify facilities to read related resources, so that this data can be included when requested. That might look like the line below, and the response is ideally fully compliant with the JSON API specification:
GET //api/my-resources/1?include=related-resource
However, a model should never create (POST), update (PUT) or delete (DELETE) these relations, not at all without explicit instructions to do so.
If you have a procedure where a model and its nested models (I assume related models) are to be created in a single go, an extra endpoint can be created for this action. You'd have to come up with a sensible name for that set of resources, and use that throughout your application's HTTP/support layer.For instance, for creation of such a set, the request might be:
POST //api/sensible-name { your: 'data' }
Keep the { your: 'data' }
part as close to a typical JSON API format as possible, preferably fully compliant. Then, in your back-end (I suppose Laravel, inn your case) you'd want to create a factory implementation that might be called <SensibleName>Factory that takes care of figuring out how to map the posted data to different models, and how their relations should be specified. Under the hood, this factory just uses the model classes' creation facilities to get you where you want to go.
When you would instead automate this process in your model it would be impossible to create the resources independently.
When you would instead automate this process in any single-resource controller that would be non-compliant with the REST paradigm.
With the factory pattern, you explicitly use that class to perform the higher level action, and none of the above concerns apply, not speaking about whether this approach is in accordance with REST at all.
The key takeaway is that the exact same result must still be achievable by performing multiple requests to single-resource endpoints, and your additional /api/sensible-name endpoint just substitutes for the need to call to those multiple endpoints, for the purpose of convenience, when you DO want to create multiple records in a single go.
Note that my statement has little to do with what endpoints to create to fetch nested resources. This SO question has some pretty good conversation as to what is acceptable, and how your specific needs might relate to that.
In the end, it's all about what works for you and your application, and REST and the like are just philosophies that propose to you an approach for similar needs in general web development as well as possible.
Below are two ways a service layer can be implemented in an CodeIgniter application.
1st method
1.send request to the controller
2.calling service layer methods from controller
3.return processed result data set(D1) from service layer to controller
4.then according to that data set controller demand data from model
5.model return data set(D2) to the controller
6.then controller send second data set(D2) to view.
2nd method
1.send request to the controller
2.calling service layer methods from controller
3.service layer demand data from model
4.model send requested data set(d1) to the service layer
5.after some processing return generated data(d2) to controller from service layer
6.then controller send data set(d2) to view.
What is the correct way of implementing a service layer in CodeIgniter? Other than these two methods, are there any other good ways?
if you can provide an example in Code it will be great
Please note, this is not necessarily the correct way of doing it, but I'm going to explain how a framework like might typically do it and then you can learn about other methods and decide the best one for your use-case. Therefore, I do not expect this answer to be the correct one, but I hope it imparts at least a little knowledge on how things are done before someone who actually knows what they're talking about comes along and chimes in (also to those people - please feel free to edit / downvote this answer :D). Finally this also has nothing to do with CodeIgniter but frameworks in general. Your question should not only be framed as framework-agnostic, but language-agnostic also.
So I'm going to offer an opinion here and that is of the fact that all modern frameworks, specifically in PHP, do not do MVC. Why is this important? Because we all need to be speaking the same language, and 'mvc' does not exist in PHP. That's a fact. Accept that and then we can move forward onto the bastardization of the concept that frameworks use; and CodeIgnitor is a particularly great example of 'MVC' bastardization; henceforth known as "mvc" with quotes.
The plus side is that frameworks like Symfony, for example, provide an initial opinionated architecture that at least contains some form of consistency across the application, and it goes something like this:
A standard HTTP request comes in and hits the front-controller, typically app.php or app_dev.php depending on whether or not you are in development or production; one involves a lot of caching that needs to be run on each change and the other doesn't - which is perfect for development.
A router matches the current url to a controller class and an 'action' (method) within that class.
The dependency injection part of the framework figures out what objects are needed for everything from the controller forward into the model layer and back, and either instantiates or prepares to instantiate them when needed.
The controller is instantiated with any required dependencies and the relevant method is executed. This is typically where you would start your development and 'hook your code in' to the framework.
This is where you decide on your architecture, however, the most important thing from both a developer perspective and business perspective (for lower costs for future maintenance) is consistency.
I personally prefer to ensure my code is decoupled from the framework. I pass in scalars taken from the request into an application-layer service, which uses objects from the model layer (passed-in via DI) to use domain objects. The point here is that domain objects are not directly passed into the controller, they are proxied through an application-layer medium, so you can theoretically replace the entire framework surrounding this and still, all you need to do is pass those scalars into this layer before they hit the model layer and it'll all still work (think CLI calls, no more controllers).
The application-level service uses any required Repositories, Services etc (and passes those scalars into them, remember the separation?), which perform business logic, (typically these are where your design patterns come into play on a day-to-day basis), and then return that data to the application-level service.
The service then returns the data to the controller and guess what? This is where frameworks tend to fuck up! Because there is no concept of a "View" in today's frameworks. There is only a template, and you pass that data to a template and bam that's it. So in your diagram, there is absolutely no concept of a view because that's not how things are done. And to be entirely honest, I'm still using templates because they're the fastest way of doing things, but until modern frameworks get their shit together and actually start using Views, we're out of luck and have to remain steadfast when confronting the fact that some (like Laravel) refer to themselves as "mvc" frameworks.
Note, Fabien Potencier explicitly states that Symfony was not an MVC framework - at least he knows what he's talking about there. Again, this is not purist, it's important we're all speaking the same, factually correct language in computing.
So, because you like diagrams so much, here's how some might do it with today's frameworks...
This is for an application that has the concept of a Review and Criteria for each Review. And don't even get me started on Symfony forms, they're so coupled to everything they're not a serious part of any architecture.
How many effing layers do you need? We already have "MVC", in DDD we have the concept of "Application", "Domain" and "Infrastructure" seperation, so get those two working together first, then this "service layer"? Do you really need another layer, or is the above enough? Things to think about...
See, you're not stuck with the framework / http request to get the application going as a result of this separation.
See the "services" in the above diagram? They're separated from the controller so you can throw scalars from anywhere and the application will still work. I think this will give you the separation you need. It's great to do things the right way, learn how to do it, and then learn how to control yourself and be pragmatic about it when it comes to the business and it's needs, but frameworks need to sort their stuff out - and you certainly wont be writing lovely code with CodeIgniter ;)
Dependency Injection and the Adapter pattern would be a good place to start.
CodeIgniter support's neither out of the box, so you would need to write a wrapper or maybe a hook.
Your view could only support xml|html as json would need to be pre-rendered to a .json file and then returned as output but this would need to be done via code, it's easier just to return the object in that case and altered on the frontend. PHP is an embedded language which works with (xml|html)
A service model works best when it is injected(dependency injection)
into a controller/model and is listed as a property of that controller/model.
The service is then bound to an interface
For example facebook/twitter
They both have a request and response function but both follow similar patterns, yet have different endpoints.
interface SocialMediaAdapter{
public request(url);
public response();
}
public class FaceBookProvider implements SocialMediaAdapter
{
public request(url){
}
public response(){
}
}
public class TwitterProvider implements SocialMediaAdapter
{
public request(url){
}
public response(){
}
}
public class SocialMediaServiceProvider{
protected $provider = null;
public function constructor(SocialMediaAdapter $provider){
$this->provider = $provider;
}
public function fetch($url){
return $this->provider->request($url);
}
}
Dependency Injection required here
new MyController( new SocialMediaServiceProvider ( new FacebookService ) )
IMHO there is no right or wrong here:
option #1 -
If you want to re-use the service layer in multiple controllers / actions
and feed it data from different models based on the request it makes sense to go for the first one.
option 2# - However the first option could be problematic if your data model is more complicated. What if a second call to the model is needed based on the data of a first call? Using the controller for this business logic defies the whole purpose of the service layer. In this case it might be better to go for the second one.
I think the second one is the more common one.
You should use first one. Because in MVC web application, controller is used to separate your business logic from view, it's something like a gateway. You need to start processing your info using controller, from controller you should call model or service layer or anything you need & finally you should return back data to any other source from here. Your view or service layer should not directly access model.
In a MVC application it is easy to understand how the Controller extracts data from the request and updates the Model layer but I am a bit confused as to how a View is supposed to retrieve data from the Model layer when the View does not know about the request?
For example if I go to
http://www.site.com/product/view/428
I route the URL and I dispatch the request and I end up in the Controller. Nothing needs to be done in the Controller(I think?) and when it gets to my View I need the product ID but the View should not be extracting data from the Request so what do I do?
Thanks.
There are two approaches for handling this and both actually would indicate that controller in this case a significant role to play.
The fabled ways of ancients ..
The first option for resolving this issue would be adhering to classical MVC as close as possible. This kinda relates to what people mean, when they say 'you cannot do classical MVC for web'. In classical MVC the view observes model layer. And that part can actually be implemented.
If that's the approach you want to take, then you will have to learn about Observer (1), (2) pattern and how to use it in PHP (1), (2). Though there has been some push for moving away from Observer pattern.
Since I have not explored this approach in any meaningful way, I will not give any examples.
The puny trail from this decade ..
If you read Fowler's "GUI Architectures" article, you might notice the part which state that views and controllers form pairs. When applying the ideas of MVC to context of web, there are ways to benefit from it in the bootstrapping stage of application.
FYI : I'm not anymore so sure, that you can call this way "Model2 MVC". There are some significant inconsistencies. I'm gonna poke more at this nagging suspicion some more, when I'm bored.
Consider this fragment:
$router->route( $request );
$resource = $request->getParameter('controller');
$view = new {'Views\\'.$resource}($serviceFactory);
$controller = new {'Controller\\'$resource}($serviceFactory, $view);
$method = $request->getMethod(); //post, get & etc.
$command = $request->getParameter('action');
$controller->{$command.$method}($request);
$view->{$command}();
echo $view->render();
The controller fragment in your example URL would be "product" and action would contain "list". I left those names instead of resource/command pair to make it less confusing.
If you start out with a premise that views and controllers are paired to some extent (whether the pairing is cohesive or not is debatable), then you can express it by using same names. This also lets you move the initialization of view out of controller.
Another aspect which is encapsulated in the fragment above is the fact that, due to the request-response nature of web, every operation in controller will require an accompanying one in the view. And similarly to how you have actions in controllers, you can also opt to call specific, route-related methods in the view. That would remove some boilerplate conditionals from views and let you better organize the whole thing (this is kinda the "highly subjective bit").
So .. how do you turn /product/view/428 request in something visible on site?
As you probably know, the responsibility of controller is to alter the state of model layer, which in this case might code something like this:
public function getView( $request )
{
$warehouse = $this->serviceFactory->provide('warehouse');
$warehouse->chooseItem( $request->getParameter('id') );
}
The your view instance uses the primed service from model layer to acquire data:
public function view()
{
$warehouse = $this->serviceFactory->provide('warehouse');
..
..
// retrieve data about sales for product with ID: 428
$something = $warehouse->getSalesFigures();
..
}
The exact implementation of view will depend on how far off deepend you are willing to go. Two most reasonable options would be:
fetch data, inspect it and if necessary choose templates and dump data into them
use a set of presentation objects to work with model layer and based on the result bind those presentation objects to ant number of templates
my 2 cents
In MVC, A controller "controls" the flow of information between the model, where the information is "stored," and the view, where it is displayed. Therefore, the controller handles all the changes of information and interaction with the models and then sends the necessary information to a view that then displays whatever information was requested/changed/etc.
MVC is all about the separation of responsibilities.
Models are responsible for storing and modeling the application's data.
Views are responsible for displaying information to the user.
Controllers actually have multiple responsibilities:
Deciding when to Create new instances of a Model.
Deciding which instances of Models to Read and passing them to the appropriate View.
Deciding which data in a Model instance needs to be Updated based on data passed back from a View.
Deciding when to Delete no longer needed instances of a Model.
In other words, Controllers sit between the Models and Views and do all the business logic for an application, including figuring out which CRUD operations need to happen... although the actual CRUD operations are usually part of the Model itself.
A better name for MVC would probably be MCV to stress how the Controller sits between the Model and View.
Newbie question about MVC structures here. So in an MVC, I currently have a page in my Views to display a list of results from a database query, in this bit of code I instantiate a class, run a method for sql query, and at last there's a for each loop and then displaying it with divs.
So my question is, if this bit of code is considered business logic and should be in a method in the Model, or is it part of the Views?
I hope you understand what I mean =) Thanks!
$listholder = new Categories_Model();
$data = $listholder->getCategories();
$i = 1;
foreach ($data as $row) {
if ($i & 1) {
echo '<div id="horizontalContainer" style="float: none; height: 50px";>';
echo '<div id="listoverview1">'.$row['catname'].'';
echo '</div>';
} else {
echo '<div id="listoverview1">'.$row['catname'].'';
echo '</div></div>';
}
$i++;
}
No, that code is mainly view code. It only purpose is to allow an external process (a human) to see data in a form it likes. Assuming that the check for the first row is only important to the external process, not to your business logic
Model code shapes, gets, and sets data, some of which is persisted (database etc.) and some of which is calculated on demand
Some generalised, and simplified examples on things a model or view should do:
Model calculates the total of some financial figures
View flags each even numbered row so it can be rendered with a shaded background in the view
Also, in a classical MVC system, your first two lines of code would be in the controller, which would organise the dataset by using models and model methods to get data. The MVC system would then pass that data to the selected view to render
There are plenty of PHP based MVC frameworks like CAKE, KISS etc (not all are very good!). If you have a few dollars in your pocket, save yourself some time and stress, and load up Microsoft MVC
From your question you might have some understanding of MVC that has nothing to do with what other developer think what MVC is. That can happen, especially nowadays as some frameworks have used these three letters as a catchphrase without providing it actually.
From the code you outline in your question I'd say it is a typical Transaction Script and there is no specific kind of model nor view layer involved.
The transaction script transports business logic and you do not need to speculate a lot about view or models, just keep everything inside the transaction script.
Your transaction scripts will tend to become spaghetti code, however, with some little refactorings here and there over time you should be able to reduce duplicate code and I do not think your application will grow that large that it is actually not feasible any longer keep it maintained in transaction scripts.
So why being concerned about MVC if everything is in order with some other, well proven pattern?
Taking as an example Rails or CakePHP, your code doesn't follow the mvc pattern.
Model should only contain business logic (query/do something with fields of an object)
Controller should work "only" with receiving requests of webpage with params and send back the correct page
View Is basically an html page only
Obviusly this is a very short briefing of what html is.
In your case, the idea would be:
$listholder = new Categories_Model();
$data = $listholder->getCategories();
Which is a controller code (usually), getCategories is a Model method (ok as is).
Then the controller will send some parameters to view which will know how to display those to the user, in this case your $data variable.
Imagine something like printMyView($view_file_path, $data)
The view will be something like this:
categories/show/">';
categories/show/">';
See http://php.net/manual/en/control-structures.alternative-syntax.php for alternative control structure syntax (quite nice). Maybe URLS are written better with sprintf or things like that (not how I did).
Basically you need 3 files (to split things logically), and the law is quite easy: don't write ever html in Controller, nor in Model.
The goal of MVC design pattern is to separate the presentation from the domain business logic. For that reason the business logic stays exclusively in model layer (model is a layer not any single class, if you have a class named Model, you are doing it wrong), whole the presentation layer contains views an controllers.
Controller instances are one that deal with user's requests, and change the state of model an view instances.
The view instances are the ones, that contain the presentation logic (just like domain objects contain the business logic in model layer). Views acquire information from model layer and decide, which templates will be used, or even whether template is even necessary. Views generate the response in your web site, and sending of redirect header is form of response too, which does not require any templates at all.
Also, you have to understand, that it is impossible to use classical MVC pattern with PHP (and highly complicated and impractical in the few web development, that would provide such option). Instead you would be using one of the MVC-inspired patterns.
These patterns are mostly distinguishable by how* view acquires information from model layer. The main options are: Model2 MVC, MVP, MVVM and HMVC.
In your case, the view should acquire the set of categories from model layer and then, if list is not empty and no exceptions were thrown, select a template which generates an unsorted HTML list.
The business logic would stay in the the model layer (in the domain object, which deals with categories), the presentation logic in the view and the process of turning it all in HTML - in the template, which view picked.
I'm learning the Zend Framework and it uses a MVC model.
I still have not got my head around what MVC Model, View, Controller is.
What are the three different areas for and what would the program flow look like?
M - Models - are often the biggest source of confusion. These are the parts of your application that do all the 'heavy lifting' - they handle database access, perform the complex application-specific logic and are responsible for most of what your application 'does'. Unlike Views and Controllers, the Zend Framework doesn't have a base class for Models - this is because there's no real consistency in what they do. Some frameworks (like Ruby on Rails) try to present some sort of database-wrapper as a base for Model, but there are many cases (3rd party feed/API, static files, non-persistent calculations, concepts that span multiple tables...) for which this is, at best, a misleading practice. The Model is the part of the application where you're still forced to program and the framework can't really save you from it.
V - Views - are the simplest components here. They should be simple PHP/HTML templates. They're given view objects, arrays, strings, etc. which they then put into a page. There shouldn't be much (if any) complex logic here - loop over these, display this (if defined), zebra stripe this table and whatnot. There's some magic happening with View Helpers (such as the helper that magically renders a Zend_Form), but that's not essential to understanding the overall system.
C - Controllers - In the broadest sense, the controller is responsible for taking user requests, sending them off to Model objects and preparing Models to be handed to the Views. It's the glue that holds everything together. If you're using Zend MVC, you're concerned with 2 controllers - Zend_Controller_Front and Zend_Controller_Action.
Zend_Controller_Front (which you get 'for free' if you use Zend_Layout::startMVC()) is a single point of entry for your application - it handles the raw user requests and translates URLs into an Action to call. There are various places to 'plug-in' to this to handle things like authentication and access restrictions, but, at the core it's just the 'traffic cop' at the front gate directing incoming requests.
Zend_Controller_Action is the base class for actions - essentially an Action represents something your application does (log in, list blog entries, launch an ICBM, order a pizza...), but is not directly responsible for actually doing it. The Action Controllers are pretty boring - they pull values out of forms and URLs, call a few methods on Model classes to actually perform the action and push the results out into the view. As has been said before, they're the 'glue' that holds Models and Views together.
A rough test to see if you're splitting things along the right lines is to envision a major change to your site. A visual redesign would almost entirely be handled in the Views. Moving all your URLs would change your Controllers. Converting from a web app to a GUI app would replace the views and controllers, but your model would still be mostly unchanged. If you rewrite your models, you have a whole new application.
There are several other questions on Stackoverflow that give an explanation of the MVC concept:
What are MVP and MVC and what is the difference?
What is MVC (Model View Controller)?
A very good explanation of the concept can be found on Wikipedia:
Model-view-controller (MVC) is an
architectural pattern used in software
engineering. Successful use of the
pattern isolates business logic from
user interface considerations,
resulting in an application where it
is easier to modify either the visual
appearance of the application or the
underlying business rules without
affecting the other. In MVC, the model
represents the information (the data)
of the application; the view
corresponds to elements of the user
interface such as text, checkbox
items, and so forth; and the
controller manages the communication
of data and the business rules used to
manipulate the data to and from the
model.
In relation to Zend Framework:
models are generally presented by extensions of the Zend_Db_Table class
views are presented as *.phtml files in your defined scripts folder, which are handled by the Zend_View class.
controllers are defined by extensions of the Zend_Controller_Action class.
The Zend Framework has its own very nice Quick Start/Tutorial which especially introduces MVC.
Quote from there:
So what exactly is this MVC pattern
everyone keeps talking about, and why
should you care? MVC is much more than
just a three-letter acronym (TLA) that
you can whip out anytime you want to
sound smart; it has become something
of a standard in the design of modern
web applications. And for good reason.
Most web application code falls under
one of the following three categories:
presentation, business logic, and data
access. The MVC pattern models this
separation of concerns well. The end
result is that your presentation code
can be consolidated in one part of
your application with your business
logic in another and your data access
code in yet another. Many developers
have found this well-defined
separation indispensable for keeping
their code organized, especially when
more than one developer is working on
the same application.
In as few words as possible:
model is the db
view is what you see (the page)
controller is the glue (logic)
Your models know how to access tables containing your data; your views know how to display content; and your controllers glue it together (what view do I show? what model should I use?).