tags:

views:

126

answers:

5

I'm trying to understand the MVC pattern. Here's what I think MV is:

Model:

<?php 
if($a == 2){
    $variable = 'two';
}
else{
    $variable = 'not two';
}
$this->output->addContent($variable);
$this->output->displayContent();
?> 

View:

<?php 

class output{

    private $content;

    public function addContent($var){
        $this->content =  'The variable is '.$var;
    }

    public function displayContent(){
        include 'header.php';
        echo $content;
        include 'footer.php';
    }

}
?>

Is this right? If so, what is the controller?

+1  A: 

Controllers receive user requests - usually there is some kind of router that takes a URL and routes the request to the appropriate controller method.

Models are used by a controller to query data to/from a database (or other data source).

Views are called from a controller to render the actual HTML output.

Justin Ethier
+1  A: 

The controller is your logic, the model is your data, and the view is your output.

So, this is the controller:

$model = new UserDB();
$user = $model->getUser("Chacha102");
$view = new UserPage($user->getName(), $user->getEmail());

echo $view->getHTML();

The model is the UserDB class which will give me my data. The view is the UserPage that I give the data from the model to, and it will then output that page.

As you can see, the controller doesn't do much in this example, because you are simply getting user data and displaying it. That is the beauty of MVC. The controller doesn't have to deal with the User SQL or HTML stuff, it just grabs the data and passes it to the view.

Also, the view doesn't know anything about the model, and the model doesn't know anything about the view. Therefore, you can chance the implementation of either, and it won't affect the other.


Relating more to your example, you have the view correct, but you have mixed your controller and model.

You could relieve this by:

Controller:

$model = new NumberToWord();
$word = $model->getWord($a);
$this->output->addContent($word);
$this->output->displayContent();

Model:

class NumberToWord{
    public function getWord($number)
    {
        if($number == 2){
            return 'two';
        }
        else{
             return 'not two';
        }
    }
 }

And keep your same output

Chacha102
For added clarification, the view is typically very simple. In this case, `getHTML()` could be simply this: `return "<html>...$user, $email...</html>";`. The controller is where most of your php code will probably go. Your html/css/js will go into views. Your models will be simple data containers (usually).
Michael Haren
Could either of you comment how ajax might fit into all this? Or is MVC not a good choice with Ajax?
Cam
So a model is basically the object and the controller acts as a go-between for the model and the view?
waiwai933
@wai Yes. The controller is there to bridge the model and the view. This is especially good when you have a lot of models or views, as the controller decides which go together.
Chacha102
AJAX is used by the web front-end (JavaScript), while MVC is used by the back-end (PHP). So the two are really mutually exclusive - however, for MVC to work with AJAX, your view only needs to return XML or JSON, not HTML.
Justin Ethier
@incrediman Javascript/AJAX are annoying in the fact that the entire thing is asynchronous, so if you have to make an AJAX call to grab data, like you would make a MySQL query in PHP, you can't just return the data back to the main controller.
Chacha102
@Justin Not necessarily true. MVC is a structural pattern that can be applied to almost any language. I can write an entire Javascript program with MVC principles, but I wouldn't be able to use non-synchronous techniques.
Chacha102
Models have the logic that manipulate "the data". Controllers accept user input and manipulate the models.
erisco
@Chacha - Fair enough, I was thinking of PHP MVC in the context of the original question.
Justin Ethier
So then if I was to use MVC with PHP for a site which uses ajax, could I have two 'separate' MVC systems? One for the PHP end of things where there's a model, controller and a view which generates html - and then another where the view is the actual html page, and the controller is the PHP script receiving the ajax messages?
Cam
@icrediman No. When I was talking about a Javascript MVC, I was talking about if you build a complex web application, you could make it in an MVC pattern. Like Gmail for instance, which is pretty much JS based, could be built in a MVC pattern. StackOverflow's Javascript, in contrast, would be pretty difficult to build in an MVC pattern, as there really isn't any logic driving the whole page, just a lot of onClick hooks.
Chacha102
Actually, I think ajax and MVC go together quite well. For example, with SO, if you have a Question controller, with an Upvote action, it can be quite simple to call that Upvote action from the client, which will execute the upvote and return a status code.
Michael Haren
A: 

If all you want to do is create a simple template system, you might aswell go with:

$content = 'blaba';
$tpl = file_get_contents('tpl.html');
echo str_replace('{content}',$content,$tpl);

With a template file like:

<html>
<head><title>Whatever</title></head>
<body>{content}</body>
</html>
Robus
A: 

Zend Framework: Surviving The Deep End has some good sections explaining MVC. Check out the MCV Intro and especially this seciton on the model.

There are numerous interpretations of the Model but for many programmers the Model is equated with data access, a misconception most frameworks inadvertently promote by not obviously acknowledging that they do not provide full Models. In our buzzword inundated community, many frameworks leave the definition of the Model unclear and obscured in their documentation.

To answer "where's the controller":

Controllers must define application behaviour only in the sense that they map input from the UI onto calls in Models and handle client interaction, but beyond that role it should be clear all other application logic is contained within the Model. Controllers are lowly creatures with minimal code who just set the stage and let things work in an organised fashion for the environment the application operates in.

I think you'll fine it (and his references of other articles and books) a good read.

Tim Lytle
+1  A: 

In your example, it's more like you've split a Controller into a Model and a View.

  • Model: Business logic / rules and typically some sort of database to object relational mapping
  • Controller: Responds to url requests by pulling together the appropriate Model(s) and View(s) to build an output.
  • View: The visual structure the output will take. Typically a "dumb" component.

It can be confusing when you first encounter MVC architecture for a web app, mainly because most web frameworks are not MVC at all, but bear a much closer resemblance to PAC. In other words, the Model and View don't talk, but are two elements pulled together by the context the Controller understands from the given request. Check out Larry Garfield's excellent commentary on the subject for more information:

http://www.garfieldtech.com/blog/mvc-vs-pac

Also, if you are interested in the MVC pattern of development, I suggest you download one of the many frameworks and run through a tutorial or two. Kohana, CodeIgnitor, CakePHP, and Zend should be enough to kick-start a Google-a-thon!

MatW