I have been struggling with understanding Model, View, Service, Controller architecture and wrote some code.
- Is my
Model
class the Model part of MVC (did I define it properly)? - Is my
Service
class a Service Layer (did I define the layer properly)? - Did I connect my layers properly (is the 'wiring' set up correctly)?
/*
* Application Idea: Assume UI has two input boxes and a button and an output box
* box A is for a number
* box B is for a number
*
* event of a button click sends responce of (A+B) into the output button
* Implement Controller, Service, Model, View layers
*/
class Controller
{
/**
*
* @var Service
*/
private $service;
/**
*
* @var Model
*/
private $model;
// add A B update C for all
function addAB()
{
$a = $this->model->getA();
$b = $this->model->getB();
$c = $this->service->computeSum($a, $b);
$this->model->setC($c);
$view = new View();
return $view->render($a, $b, $c);
}
public function getService()
{
return $this->service;
}
public function setService($service)
{
$this->service = $service;
}
public function getModel()
{
return $this->model;
}
public function setModel($model)
{
$this->model = $model;
}
}
class ControllerFactory
{
function getController(array $request)
{
$model = new Model();
$model->setA($request['a']);
$model->setB($request['b']);
$service = new Service();
$controller = new Controller();
$controller->setService($service);
$controller->setModel($model);
return $controller;
}
}
class Model
{
private $a;
private $b;
private $c;
public function getA()
{
return $this->a;
}
public function getB()
{
return $this->b;
}
public function getC()
{
return $this->c;
}
public function setA($a)
{
$this->a = $a;
}
public function setB($b)
{
$this->b = $b;
}
public function setC($c)
{
$this->c = $c;
}
}
class Service
{
function computeSum($a, $b)
{
return $a + $b;
}
}
class View
{
function render($a, $b, $c)
{
print "$a + $b = $c";
}
}
class Router
{
function routeRequest($request)
{
$controller = (new ControllerFactory())->getController($request);
switch ($request['event'])
{
case 'add_event':
$controller->addAB();
break;
}
}
}
/*
* request can come from Web Browser
*/
$request = array();
$request['event'] = "add_event";
$request['a'] = 2;
$request['b'] = 3;
$router = new Router();
$router->routeRequest($request);