Skip to content

Commit

Permalink
Consolidate handler function parameters into one App param or types p…
Browse files Browse the repository at this point in the history
…arameters.
  • Loading branch information
ringmaster committed Nov 30, 2012
1 parent affb5e2 commit c4ab9cd
Show file tree
Hide file tree
Showing 9 changed files with 146 additions and 74 deletions.
65 changes: 36 additions & 29 deletions index.php
@@ -1,11 +1,14 @@
<?php

use \Microsite\App;
use \Microsite\Regex;
use \Microsite\Response;
use \Microsite\Request;
use \Microsite\DB\PDO\DB;
use \Microsite\Handler;
use Microsite\App;
use Microsite\Regex;
use Microsite\Response;
use Microsite\Request;
use Microsite\DB\PDO\DB;
use Microsite\Handler;
use Microsite\Tinycode;
use Microsite\Renderers\JSONRenderer;
use Microsite\DB\Mongo\DB as MongoDB;

include 'src/microsite.phar';
//include 'src/stub2.php';
Expand All @@ -21,8 +24,8 @@
* Basic home page.
* Set the view to a home.php view provided in the view directory
*/
$app->route('home', '/', function(Response $response) {
return $response->render('home.php');
$app->route('home', '/', function(App $app) {
return $app->response()->render('home.php');
});

/**
Expand All @@ -43,21 +46,21 @@
/**
* Route with a parameter
*/
$app->route('hello', '/hello/:name', function(Response $response, Request $request) {
$app->route('hello', '/hello/:name', function(Request $request) {
echo "Hello {$request['name']}!";
});

/**
* Route with a validated parameter
*/
$app->route('count', '/count/:number', function(Response $response, Request $request) {
$app->route('count', '/count/:number', function(Request $request) {
echo "This is a number: {$request['number']}";
})->validate_fields(['number' => '[0-9]+']);

/**
* Route with a validated parameter function, only /valid/ok correctly routes here
*/
$app->route('valid', '/valid/:valid', function(Response $response, Request $request) {
$app->route('valid', '/valid/:valid', function(Request $request) {
echo "This is a valid route: {$request['valid']}";
})->validate_fields(['valid' => function($value) {return ($value == 'ok');}]);

Expand All @@ -68,15 +71,16 @@
->route(
'user',
'/user/:user',
function(Response $response, Request $request) {
echo "The requested user's name is: {$request['user']->name}";
function(Request $request, Response $response) {
$response['output'] = '<pre>' . print_r($request['user'], 1) . '</pre>';
return $response->render('debug.php');
}
)
->validate_fields([':user' => '\d+'])
->convert('user', function($user_id){
$user = new stdClass(); // Simulate getting a database record.
$user->id = $user_id;
$user->name = 'Test User';
$user->name = 'Test User #' . $user_id;
return $user;
});

Expand All @@ -86,12 +90,12 @@ function(Response $response, Request $request) {
$app->route(
'evenodd',
'/evenodd/:number',
function(Response $response, Request $request) {
function(Request $request) {
if($request['number'] % 2 == 0) {
echo "This is an even number";
}
},
function(Response $response, Request $request) {
function(Request $request) {
if($request['number'] % 2 == 1) {
echo "This is an odd number";
}
Expand All @@ -102,7 +106,7 @@ function(Response $response, Request $request) {
/**
* Use the route system to produce the url to the named route "hello"
*/
$app->route('interior', '/interior', function(Response $response, Request $request, App $app) {
$app->route('interior', '/interior', function(Response $response, $app) {
$response['output'] = $app->get_route('hello')->build(['name' => 'User']);
return $response->render('debug.php');
});
Expand All @@ -111,7 +115,7 @@ function(Response $response, Request $request) {
/**
* A simple custom Handler class
*/
class MyHandler extends \Microsite\Handler {
class MyHandler extends Handler {
public $prerequisite;

public function handler_one() {
Expand Down Expand Up @@ -162,7 +166,7 @@ public function handler_two() {
$app->route(
'form_post',
'/form',
function($response) {
function(Response $response) {
if(trim($_POST['name']) == '') {
$response->redirect('/form');
}
Expand Down Expand Up @@ -212,7 +216,7 @@ function() {
* Within the admin app, create a /plugins URL
* Output a message using the internal debug.php template
*/
$admin->route('plugins', '/plugins', function(Response $response) {
$admin->route('plugins', '/plugins', function() {
echo "This is the Plugins page";
});

Expand All @@ -239,13 +243,14 @@ function() {
* Note that the mockdb objects are the different because it was registered with ->demand()
* If it was registered with ->share() it would be created only once
*/
$app->route('json', '/json', function(Response $response, Request $request, App $app) {
$app->route('json', '/json', function(App $app) {
$response = $app->response();
$response['user'] = 'Owen';
$response['user_id'] = 1;
$response['registered'] = true;
$response['mockdb_obj'] = $app->mockdb(1);
$response['mockdb_obj2'] = $app->mockdb(16);
$response->set_renderer(\Microsite\Renderers\JSONRenderer::create(''));
$response->set_renderer(JSONRenderer::create('', $app));
return $response->render();
});

Expand All @@ -258,7 +263,8 @@ function() {
return $db;
});

$app->route('database', '/database', function(Response $response, $request, $app) {
$app->route('database', '/database', function(App $app) {
$response = $app->response();
$samples = $app->db()->results('SELECT * FROM sample ORDER BY age ASC;');

$response['output'] = $response->partial('table.php', array('results' => $samples));
Expand All @@ -269,10 +275,11 @@ function() {
* On-demand mongo
*/
$app->share('mongo', function() {
return new \Microsite\DB\Mongo\DB('samplez');
return new MongoDB('samplez');
});

$app->route('mongo', '/mongo', function(Response $response, $request, $app) {
$app->route('mongo', '/mongo', function(App $app) {
$response = $app->response();
/** @var \Microsite\DB\Mongo\DB $mongo */
$mongo = $app->mongo();

Expand All @@ -291,12 +298,12 @@ function() {
* Show a sequence of Tinycodes
*/
$app->route('tinycode', '/tiny', function(){
\Microsite\Tinycode::init();
Tinycode::init();
header('content-type: text/plain');
echo 'Total codes: ' . \Microsite\Tinycode::max_int() . "\n";
echo 'Total codes: ' . Tinycode::max_int() . "\n";
for($z = 1; $z <=300; $z++) {
$s = \Microsite\Tinycode::to_code($z);
$n = \Microsite\Tinycode::to_int($s);
$s = Tinycode::to_code($z);
$n = Tinycode::to_int($s);
echo $z . ' encoded => ' . $s . ' decoded => ' . $n . "\n";
}
});
Expand Down
95 changes: 64 additions & 31 deletions src/lib/Microsite/App.php
Expand Up @@ -9,6 +9,7 @@ class App
private $objects = array();
public $template_dirs = array();
protected $defaults = array();
public $route = null;

/**
* Constructor for App
Expand All @@ -27,6 +28,23 @@ public function __construct() {
header($header, $replace, $http_response_code);
}
);
$this->share('request', function($request = null) {
if(is_null($request)) {
return new Request([
'url' => isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '',
]);
}
return $request;
});
$this->share('response', function($response = null) {
if(is_null($response)) {
return new Response([
'renderer' => $this->renderer(),
'app' => $this,
]);
}
return $response;
});
}


Expand Down Expand Up @@ -72,38 +90,28 @@ public function get_url($name, $args = []) {

/**
* Run the app, parsing the requested URL and dispatching to the appropriate Route
* @param Request|null $request A Request to process, if null, default to $_SERVER['REQUEST_URI']
* @param Response|null $response A Response to render to
* @param App|null $parent
* @return bool|string Upon successful execution, the string of output produced, otherwise false
*/
public function run($request = null, $response = null, $parent = null) {
public function run() {
try {
$null_response = false;
$do_output = false;
$has_output = false;

if(is_null($request)) {
$request = new Request([
'url' => $_SERVER['REQUEST_URI'],
]);
}
$request = $this->request();
$response = $this->response();

if(is_null($response)) {
$response = new Response([
'renderer' => $this->renderer(),
'app' => $this,
]);
$null_response = true;
if(!$response->did_output) {
$response->did_output = true;
$do_output = true;
}

$this->parent = $parent;

$output = false;
foreach($this->routes as $route) {
/** @var Route $route */
if($route->match($request)) {
$request['_route'] = $route;
$response['_app'] = $this;
$result = $route->run($response, $request, $this);
$this->route = $route;
$result = $route->run($this);
if($result) {
$output = (string) $result;
$has_output = true;
Expand All @@ -112,7 +120,7 @@ public function run($request = null, $response = null, $parent = null) {
}
}

if($null_response) {
if($do_output) {
if($has_output) {
echo $output;
}
Expand All @@ -138,26 +146,23 @@ public function run($request = null, $response = null, $parent = null) {
/**
* Allow this object to be executed directly
* Example: $app = new App(); $app();
* @param Response|null $response A Response to render to
* @param Request|null $request A Request to process, if null, default to $_SERVER['REQUEST_URI']
* @param App|null $parent
* @return bool|string Upon successful execution, the string of output produced, otherwise false
*/
public function __invoke(Response $response = null, Request $request = null, App $app = null) {
public function __invoke() {
$request = $this->request();
if(isset($request['match_url'])) {
$request = new Request([
'url' => $request['match_url'],
]);
$request['url'] = $request['match_url'];
}
return $this->run($request, $response, $app);
return $this->run();
}

/**
* Simulate a specific URL request
* @param string $url The URL request to simulate
* @return bool|string Upon successful execution, the string of output produced, otherwise false
*/
public function request($url) {
public function simulate_request($url) {
$_SERVER['REQUEST_URI'] = $url;
return $this->run();
}
Expand All @@ -181,19 +186,47 @@ public function demand($object_name, Callable $callback) {
}

/**
* Magic method __call(), used to invoke registered dependency injections
* Get the Request object to use with this App
* @return Request The request object for this App
*/
public function request() {
return $this->dispatch_object('request', []);
}

/**
* Get the Response object to use with this App
* @return Response The response object for this App
*/
public function response() {
return $this->dispatch_object('response', []);
}

/**
* Internal method to invoke registered dependency injections
* @see App::share
* @see App::demand
* @param string $name The name of the method that was called on this object instance
* @param array $args The arguments that were used in the call
* @return mixed The result of the dependency injection or the default methods (added in App::__construct)
*/
public function __call($name, $args) {
protected function dispatch_object($name, $args) {
if(isset($this->objects[$name])) {
$call_object = $this->objects[$name];
return $call_object->invoke($args);
}
return null;
}

/**
* Magic method __call(), used to invoke registered dependency injections
* @see App::share
* @see App::demand
* @param string $name The name of the method that was called on this object instance
* @param array $args The arguments that were used in the call
* @return mixed The result of the dependency injection or the default methods (added in App::__construct)
*/
public function __call($name, $args) {
return $this->dispatch_object($name, $args);
}

}
4 changes: 2 additions & 2 deletions src/lib/Microsite/Handler.php
Expand Up @@ -17,7 +17,7 @@ class Handler
* @return callable A Closure used in a call to App::Route() that is used as a handler
*/
public static function handle($class, $method) {
$fn = function(Response $response, Request $request, App $app) use($class, $method) {
$fn = function(App $app) use($class, $method) {
if(isset(Handler::$instances[$class])) {
$handler_obj = Handler::$instances[$class];
}
Expand All @@ -26,7 +26,7 @@ public static function handle($class, $method) {
$handler_obj = $r_class->newInstanceArgs();
Handler::$instances[$class] = $handler_obj;
}
return $handler_obj->$method($response, $request, $app);
return $handler_obj->$method($app);
};
return $fn;
}
Expand Down
4 changes: 3 additions & 1 deletion src/lib/Microsite/Renderers/Renderer.php
Expand Up @@ -5,6 +5,8 @@
/**
* Abstract class for implementing a renderer of output
*/
use Microsite\App;

abstract class Renderer
{
/**
Expand All @@ -21,7 +23,7 @@ abstract class Renderer
* Create a new Renderer, configuring its template directories
* @param string|array $template_dirs A template directory or an array of potential directories
*/
public function __construct($template_dirs, \Microsite\App $app) {
public function __construct($template_dirs, App $app) {
if(!is_array($template_dirs)) {
$template_dirs = array($template_dirs);
}
Expand Down

0 comments on commit c4ab9cd

Please sign in to comment.