Skip to content

Instantly share code, notes, and snippets.

@JohnMurray
Last active December 14, 2015 19:49
Show Gist options
  • Save JohnMurray/5139047 to your computer and use it in GitHub Desktop.
Save JohnMurray/5139047 to your computer and use it in GitHub Desktop.
gists for blog post on Pinatra (PHP Sinatra clone) as a tool for learning
Pinatra::after('*', function () {
Logger::log_request('served yet another request');
});
Pinatra::before('*', function () {
header('AppVersion: 0.0.1');
});
Pinatra::get('/hi', function () {
return 'hello world';
});
Pinatra::get('/hello/:name', function($name) {
return $this->json([
'key' => 'hello-route has been matched!',
'name' => $name
]);
});
/**
* Method that is called when we actually want to process an incoming
* request based on the method and uri provided. This method (expecting
* to be given a URI and method) can also be used for re-routing requests
* internally.
*/
public static function handle_request($method, $uri) {
$app = Pinatra::instance();
// before hook code (removed for brevity)
// find and call route-handler
$route_match = $app->find_route($app->routes, $method, $uri);
if ($route_match !== null) {
$request_body_data = $app->get_body_data($method);
if ($request_body_data !== null) {
array_unshift($route_match['arguments'], $request_body_data);
}
$route_res = call_user_func_array(
$route_match['callback']->bindTo($app),
$route_match['arguments']);
}
// after hook code (removed for brevity)
}
public static function get($match, $callback) {
$app = Pinatra::instance();
$app->register('get', $match, $callback);
}
private $URIParser_PLACEHOLDER = '([^\/]+)';
private $URIParser_GLOB = '.*?';
/**
* Private: Generate a PHP (Perl) regular expression given the
* Sinatra-style expression in the get/post/put/etc. functions.
*/
private function compute_regex($match) {
// get the URI parts of the match-pattern given
$parts = array_filter(explode('/', $match), function ($val) {
return !empty($val);
});
// build our pattern-matching regex from given route
$regex= '/^';
foreach ($parts as $part) {
if ($part[0] === ':') {
$regex .= '\/' . $this->URIParser_PLACEHOLDER;
}
else if ($part[0] === '*'){
$regex .= '\/' . $this->URIParser_GLOB;
}
else {
$regex .= '\/' . $part;
}
}
$regex .= '\/?$/';
return $regex;
}
private function register($method, $match, $callback) {
$match = $this->compute_regex($match);
$this->routes[$method][$match] = $callback;
}
Pinatra::post('/name', function ($data) {
return 'Hello ' . $data['name'];
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment