Created
September 4, 2014 19:46
-
-
Save jm42/ec8783eee0814b31a737 to your computer and use it in GitHub Desktop.
Request Stack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Request | |
{ | |
public $controller; | |
public $vars; | |
public function __construct(array $vars = array()) | |
{ | |
$this->vars = $vars; | |
} | |
public function get($name, $default = '') | |
{ | |
if (array_key_exists($name, $this->vars)) { | |
return $this->vars[$name]; | |
} | |
return $default; | |
} | |
} | |
class Http | |
{ | |
public function handle(Request $request, array $stack = array()) | |
{ | |
$stack[] = $request; | |
$response = call_user_func($request->controller, $stack); | |
return $response; | |
} | |
} | |
class Controller | |
{ | |
protected $http; | |
public function __construct(Http $http) | |
{ | |
$this->http = $http; | |
} | |
protected function handle($action, array $requests) | |
{ | |
$request = new Request(); | |
$request->controller = array($this, $action); | |
$response = $this->http->handle($request, $requests); | |
$response .= $this->calledFrom($requests); // Inside the handle should | |
// not be last one, but the | |
// previous one. | |
return $response; | |
} | |
protected function calledFrom(array $requests) | |
{ | |
return '(' . $this->currentRequest($requests)->controller[1] . ')'; | |
} | |
protected function currentRequest(array $requests) | |
{ | |
return $requests[count($requests) - 1]; | |
} | |
} | |
class Dashboard extends Controller | |
{ | |
public function index(array $requests) | |
{ | |
$widgets = $this->handle('widgetHello', $requests) | |
. $this->handle('widgetStats', $requests); | |
return 'Widgets{' . $widgets . '}'; | |
} | |
public function widgetHello(array $requests) | |
{ | |
$request = $this->currentRequest($requests); | |
$name = $request->get('name', 'World'); | |
return 'Hello ' . $name; | |
} | |
public function widgetStats(array $requests) | |
{ | |
$stats = $this->handle('statsVisits', $requests) | |
. $this->handle('statsHits', $requests); | |
return 'Stats{' . $stats . '}'; | |
} | |
public function statsVisits(array $requests) | |
{ | |
return 'Visits:123'; | |
} | |
public function statsHits(array $requests) | |
{ | |
return 'Hits:321'; | |
} | |
} | |
$http = new Http(); | |
$request = new Request($_GET); | |
$request->controller = array(new Dashboard($http), 'index'); | |
$response = $http->handle($request); | |
echo $response . PHP_EOL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment