Skip to content

Instantly share code, notes, and snippets.

@Daniel-Griffiths
Created June 19, 2017 20:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Daniel-Griffiths/53082476c3c76ff0bf981a8bc406b611 to your computer and use it in GitHub Desktop.
Save Daniel-Griffiths/53082476c3c76ff0bf981a8bc406b611 to your computer and use it in GitHub Desktop.
Random small router
<?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