Skip to content

Instantly share code, notes, and snippets.

@arka816
Last active April 25, 2021 06:45
Show Gist options
  • Save arka816/f1c78d8b6db38e049143ed997129c236 to your computer and use it in GitHub Desktop.
Save arka816/f1c78d8b6db38e049143ed997129c236 to your computer and use it in GitHub Desktop.
routing in php

Running the server

Modify index.php to create new routes and handlers for them keeping the basic skeleton intact. Save all files to one folder. Run the php server from the command line using:

php -S 127.0.0.1:8000
<?php
include_once "Request.php";
include_once "Router.php";
$router = new Router(new Request);
$router->get("/", function(){
return "Hola MadaFuqqa!!";
});
$router->post("/", function($request){
return json_encode($request->getBody());
});
<?php
interface IRequest{
public function getBody();
}
<?php
include_once "IRequest.php";
class Request implements IRequest{
function __construct(){
$this->bootstrapSelf();
}
private function bootstrapSelf(){
foreach($_SERVER as $key => $value){
$this->{$this->toCamelCase($key)} = $value;
}
}
public function getBody(){
if($this->requestMethod === 'GET') return;
elseif($this->requestMethod === 'POST'){
$body = array();
foreach($_POST as $key => $value){
$body[$key] = $value;
}
return $body;
}
}
private function toCamelCase($string)
{
$result = strtolower($string);
preg_match_all('/_[a-z]/', $result, $matches);
foreach($matches[0] as $match){
$c = str_replace('_', '', strtoupper($match));
$result = str_replace($match, $c, $result);
}
return $result;
}
}
<?php
class Router{
private $request;
private $supportedHttpMethods = array(
"GET",
"POST"
);
function __construct(IRequest $request){
$this->request = $request;
}
function __call($name, $args){
list($route, $method) = $args;
if(!in_array(strtoupper($name), $this->supportedHttpMethods)){
$this->invalidMethodHandler();
}
$this->{strtolower($name)}[$this->formatRoute($route)] = $method;
}
private function formatRoute($route)
{
$result = rtrim($route, '/');
if ($result === '')return '/';
return $result;
}
private function invalidMethodHandler(){
header("{$this->request->serverProtocol} 405 Method not Allowed");
}
private function defaultRequestHandler(){
header("{$this->request->serverProtocol} 404 Not Found");
}
function resolve()
{
$methodDictionary = $this->{strtolower($this->request->requestMethod)};
$formatedRoute = $this->formatRoute($this->request->requestUri);
$method = $methodDictionary[$formatedRoute];
if(is_null($method))
{
$this->defaultRequestHandler();
return;
}
echo call_user_func_array($method, array($this->request));
}
function __destruct()
{
$this->resolve();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment