Skip to content

Instantly share code, notes, and snippets.

@victorknust
Forked from dhrrgn/.htaccess
Created Oct 27, 2016
Embed
What would you like to do?
NPSR - PSRs? We don't need to stinkin' PSRs.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?_uri=$1 [L]
<?php
define('FRONT_CONTROLLER', true);
include 'npsr.php';
get('/', function ($params) {
echo 'Hello World!';
});
go();
<?php if ( ! defined('FRONT_CONTROLLER')) die('No No No');
class NpsrNotFoundException extends Exception { }
class Npsr
{
private $routes = array(
'GET' => array(),
'POST' => array(),
'PUT' => array(),
'DELETE' => array(),
'OPTIONS' => array(),
);
public function get($uri, $callback) {
$this->addRoute('GET', $uri, $callback);
}
public function post($uri, $callback) {
$this->addRoute('POST', $uri, $callback);
}
public function put($uri, $callback) {
$this->addRoute('PUT', $uri, $callback);
}
public function delete($uri, $callback) {
$this->addRoute('DELETE', $uri, $callback);
}
public function options($uri, $callback) {
$this->addRoute('OPTIONS', $uri, $callback);
}
public function go() {
$uri = $params['_uri'];
$method = $this->getMethod();
$params = $this->getParams();
if (array_key_exists('_uri', $params)) {
$uri = $params['_uri'];
unset($params['_uri']);
} else {
$uri = '/';
}
$route = null;
foreach ($this->routes[$method] as $r) {
if (preg_match('/'.preg_quote($r['uri'], '/').'/', $uri)) {
$route = $r;
break;
}
}
if ($route === null) {
throw new NpsrNotFoundException("No route for {$uri}");
}
$route['callback']($params);
}
private function addRoute($method, $uri, $callback) {
array_push($this->routes[strtoupper($method)], array('uri' => $uri, 'callback' => $callback));
}
private function getParams() {
switch ($this->getMethod()) {
case 'GET':
return $_GET;
case 'POST':
return $_POST;
default:
parse_str(file_get_contents("php://input"), $params);
return $params;
}
}
private function getMethod() {
if ( ! isset($_SERVER['HTTP_METHOD'])) {
return 'GET';
}
return strtoupper($_SERVER['HTTP_METHOD']);
}
}
$npsr = new Npsr;
function get($uri, $callback) {
global $npsr;
$npsr->get($uri, $callback);
}
function post($uri, $callback) {
global $npsr;
$npsr->post($uri, $callback);
}
function put($uri, $callback) {
global $npsr;
$npsr->put($uri, $callback);
}
function delete($uri, $callback) {
global $npsr;
$npsr->delete($uri, $callback);
}
function options($uri, $callback) {
global $npsr;
$npsr->options($uri, $callback);
}
function go() {
global $npsr;
$npsr->go();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment