I am just heading into MVC design pattern. A simple example here does not clear my concept about the use of controller. Could you please explain real use of controller while keeping it simple.
Model:
class Model {
public $text;
public function __construct() {
$this->text = 'Hello world!';
}
}
Controller:
class Controller {
private $model;
public function __construct(Model $model) {
$this->model = $model;
}
}
View:
class View {
private $model;
//private $controller;
public function __construct(/*Controller $controller,*/ Model $model) {
//$this->controller = $controller;
$this->model = $model;
}
public function output() {
return '<h1>' . $this->model->text .'</h1>';
}
}
index:
require_once('Model.php');
require_once('Controller.php');
require_once('View.php');
//initiate the triad
$model = new Model();
//It is important that the controller and the view share the model
//$controller = new Controller($model);
$view = new View(/*$controller,*/ $model);
echo $view->output();
Controllers purpose in MVC pattern is to alter the state of model layer.
It's done by controller receiving user input (preferable - abstracted as some thing like
Request
instance) and then, based on parameters that are extracted from the user input, passes the values to appropriate parts of model layer.The communication with model layer usually happens via various services. These services in turn are responsible for governing the interaction between persistence abstraction and domain/business objects, or also called "application logic".
Example:
What is controller NOT responsible for?
Controllers in MVC architectural pattern are NOT responsible for:
The controller in PHP ( or in fact in any server language, would be the one that handles the url that is called) So i will have to rewrite your above code it would be
Main file; this in fact will be your main controller or router, this is the first file that is called and usually would be called index.php ( in this file just create an instance of controller, no need to create model and view since they will be in purview of controller as to which model and view to use)
Controller file => Here instantiate the model and view. The advantage is the model and view can be changed if required in the controller itself
That's pretty much it . I dont see any code changes in your model or view files. Theu shoudl work as is except you will echo the content in view instead of returning it.