Skip to content

Instantly share code, notes, and snippets.

@Moccine
Created July 21, 2016 07:58
Show Gist options
  • Select an option

  • Save Moccine/434b5ad20e84945844cf53de35b9d74d to your computer and use it in GitHub Desktop.

Select an option

Save Moccine/434b5ad20e84945844cf53de35b9d74d to your computer and use it in GitHub Desktop.
MVC Services
<?php
namespace project\Services;
use project\Controller\Controller;
class Dispatcher
{
public $parameters;
public $action;
public $controller;
public $viewer;
public function __construct()
{
$this->viewer = new Viewer();
$this->parameters = $_GET;
}
public function dispatch()
{
$viewParameters = $this->extractActionAndController();
$controllerParameters = $this->executeAction();
$this->viewer->sethelper($this->controller)->setParameters($viewParameters)
->setViewParameters($viewParameters)
->setControllerParameters($controllerParameters)
->render();
}
public function extractActionAndController()
{
$action = isset($this->parameters['action']) ? $this->parameters['action'] : DEFAULT_ACTION;
$controller = isset($this->parameters['controller']) ? $this->parameters['controller'] : DEFAULT_CONTROLLER;
$this->action = $action;
$this->controller = $controller;
return array($controller, $action);
}
/*
* execute la method action
*/
public function executeAction()
{
$pathController = sprintf('project\\Controller\\%sController', lcfirst($this->controller));
if (!class_exists($pathController)) {
throw new \Exception(" $pathController not found ");
} else {
$controllerClass = new $pathController();
$action = sprintf('%sAction', lcfirst($this->action));
$parameters = $this->cleanParameters();
return call_user_func_array(array($controllerClass, $action), array($parameters));
}
}
/*
* Nettoie les parametres pour recuperer les arguments
*/
public function cleanParameters()
{
if (isset($this->parameters['controller'])) {
unset($this->parameters['controller']);
}
if (isset($this->parameters['action'])) {
unset($this->parameters['action']);
}
return $this->parameters;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment