Created
June 19, 2017 20:49
-
-
Save Daniel-Griffiths/53082476c3c76ff0bf981a8bc406b611 to your computer and use it in GitHub Desktop.
Random small router
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Router | |
{ | |
/** | |
* Route storage. | |
* | |
* @var array | |
*/ | |
protected $routes = []; | |
/** | |
* Request method (eg GET, POST). | |
* | |
* @var string | |
*/ | |
protected $method; | |
/** | |
* Request URI. | |
* | |
* @var string | |
*/ | |
protected $uri; | |
/** | |
* Create a new Router | |
* | |
* @param string $method | |
* @param string $uri | |
*/ | |
public function __construct($method, $uri) | |
{ | |
$this->method = $method; | |
$this->uri = $uri; | |
} | |
/** | |
* Register a new route. | |
* | |
* @param string $method | |
* @param string $uri | |
* @param string $handler | |
* @return array | |
*/ | |
public function addRoute($method, $uri, $handler) | |
{ | |
return $this->routes[$method][$uri] = explode('@', $handler); | |
} | |
/** | |
* Alias to register a new GET route. | |
* | |
* @param string $uri | |
* @param string $handler | |
* @return array | |
*/ | |
public function get($uri, $handler) | |
{ | |
return $this->addRoute('GET', $uri, $handler); | |
} | |
/** | |
* Alias to register a new POST route. | |
* | |
* @param string $uri | |
* @param string $handler | |
* @return array | |
*/ | |
public function post($uri, $handler) | |
{ | |
return $this->addRoute('POST', $uri, $handler); | |
} | |
/** | |
* Dispatch the router. | |
* | |
* @return mixed | |
*/ | |
public function dispatch() | |
{ | |
return (New $this->routes[$this->method][$this->uri][0])->{$this->routes[$this->method][$this->uri][1]}(); | |
} | |
/** | |
* Return an array of all registered routes. | |
* | |
* @return array | |
*/ | |
public function getRoutes() | |
{ | |
return $this->routes; | |
} | |
} | |
class Hello{ | |
public function world() | |
{ | |
var_dump('routing is cool'); | |
} | |
} | |
$router = New Router($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI']); | |
$router->get('/this-is-a-test', 'Hello@world'); | |
$router->dispatch(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment