2

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?

2
  • Looks more like your model is actually a controller. Models generally deal with business objects and their associated logic (Very often a database row and the manipulations required to be able to use it). Commented May 9, 2010 at 0:53
  • That is not really the MVC concept - I recommend reading through an example implementation such as codeigniter.com/user_guide to get a better idea of how MVC can be implemented in PHP. Commented May 9, 2010 at 0:54

6 Answers 6

2

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

Sign up to request clarification or add additional context in comments.

12 Comments

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).
Could either of you comment how ajax might fit into all this? Or is MVC not a good choice with Ajax?
So a model is basically the object and the controller acts as a go-between for the model and the view?
@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.
Models have the logic that manipulate "the data". Controllers accept user input and manipulate the models.
|
1

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.

Comments

1

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>

Comments

1

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!

Comments

0

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.

Comments

0

Here is a very simple example of MVC using PHP. One thing missing is THE router. It selects one of the controller to do the job. We have only one controller, the customer.

If we compare it with 3 tiers

Model: The database View: Client Server:Controller Router:It selects a controller

When you select something from an application on web browser, the request goes to router, from router it goes to controller. Controller asks from model and make a view. View is rendered to you.

Only model can talk to controller back and forth.

1- Model.php

<?php
class Model
{
    private $con=null;
    private $r=null;
   function connect()
   {    
   $host="localhost";
   $db="mis";
   $user="root";
   $pass="";
   $this->con=mysqli_connect($host,$user,$pass) or die(mysqli_error());
    if(!$this->con){
        echo die(mysqli_error());
    }
    else mysqli_select_db($this->con,$db);
   }
    function select_all()
    {
        $this->connect();
        $sql="select * from customers";
        $this->r=mysqli_query($this->con,$sql) or die(mysqli_error());
        return $this->r;
    }
    function display_all()
    {
        $i=0;
        echo "aaaaaaaaaa";
        $this->r=$this->select_all();
        while($q=mysqli_fetch_array($this->r))
        {
            $i++;
            echo $i."-Id:".$q['id']."</br>";
            echo $i."-Name:".$q['name']."</br>";
            echo $i."-Phone:".$q['phone']."</br></br>";         
        }
    }
}
?>
2. Controller: There may may be many controllers.
<?php
class Customers extends Model
{


    function select_all1()
    {
        //echo "aaaaaaa";
        $this->display_all();
    }

}
?>
3. View: There may be many views
<?php
include("model.php");
include("customers.php");
?>
<html>
<head><title>Customers</title></head>
<body>
<?php
$c=new Customers();
echo $c->select_all1();
?>
</body>
</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.