Thursday 6 June 2013

MVC in PHP

Program flow

  • The model, view and controller are initialized
  • The view is displayed to the user, reading data from the model
  • The user interacts with the view (e.g. presses a button) which calls a specified controller action
  • The controller updates the model in some way
  • The view is refreshed (fetching the updated data from the model)


<?php
class Model {
    public $text;
   
    public function __construct() {
        $this->text = 'Hello world!';
    }        
}

class View {
    private $model;
    private $controller;
   
    public function __construct(Controller $controller, Model $model) {
        $this->controller = $controller;
        $this->model = $model;
    }
   
    public function output() {
        return '<a href="helloworld.php?action=textclicked">' . $this->model->text . '</a>';
    }    
}

class Controller {
    private $model;

    public function __construct(Model $model) {
        $this->model = $model;
    }

    public function textClicked() {
        $this->model->text = 'Text Updated';
    }
}

$model = new Model();
//It is important that the controller and the view share the model 
$controller = new Controller($model);
$view = new View($controller, $model);
if (isset($_GET['action'])) $controller->{$_GET['action']}();
echo $view->output();

?>

No comments: