Skip to content

Instantly share code, notes, and snippets.

@jm42
Created September 4, 2014 19:46
Show Gist options
  • Save jm42/ec8783eee0814b31a737 to your computer and use it in GitHub Desktop.
Save jm42/ec8783eee0814b31a737 to your computer and use it in GitHub Desktop.
Request Stack
<?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