Skip to content

Instantly share code, notes, and snippets.

@jm42
Created October 23, 2014 06:42
Show Gist options
  • Save jm42/6e0941b4be6cc964f18e to your computer and use it in GitHub Desktop.
Save jm42/6e0941b4be6cc964f18e to your computer and use it in GitHub Desktop.
Template for Application class
<?php
interface Module
{
function start();
function stop();
function buildContainer(Container $container);
}
class Application
{
private $modules = [];
private $requests = [];
private $container;
private $started = false;
public function start() {
if ($this->started === true) {
return;
}
foreach ($this->modules as $module) {
$module->start();
}
$this->container = $this->buildContainer(null);
$this->started = true;
}
public function stop() {
if ($this->started === false) {
return;
}
foreach ($this->modules as $module) {
$module->stop();
}
$this->container = null;
$this->started = false;
}
public function buildContainer(Container $container) {
$root = new CompositeContainer;
if ($container !== null) {
$root->add($container);
}
foreach ($this->modules as $module) {
$subcontainer = $module->buildContainer($root);
if ($subcontainer instanceof Container) {
$root->add($subcontainer);
}
}
return $root;
}
public function run() {
return $this->handle(Request::fromEnviron());
}
public function handle(Request $request) {
$this->started || $this->start();
try {
return $this->handleRequest($request);
} catch (Exception $e) {
if (count($this->requests) > 1) {
throw $e;
}
return $this->handleException($e, $request);
}
}
private function handleRequest(Request $request) {
array_push($this->requests, $request);
array_pop($this->requests);
}
private function handleException(Exception $exception, Request $request) {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment