I'm adding a funcionality to this custom Router and custom Request Class in order to be able to serve pages and json responses.
I'm stuck on the router part, where the Route has a parameter in the url like:
example.com/apply/{variable}
Those are the classes:
Router class:
<?php
class Router
{
private $request;
private $supportedHttpMethods = array("GET", "POST");
function __construct(RequestInterface $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;
}
/**
* Removes trailing forward slashes from the right of the route.
*
* @param route (string)
*/
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");
}
/**
* Resolves a route
*/
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();
}
}
Request Class:
<?php
include_once 'RequestInterface.php';
class Request implements RequestInterface
{
private $params = [];
public function __construct()
{
$this->bootstrapSelf();
}
private function bootstrapSelf()
{
foreach ($_SERVER as $key => $value) {
$this->{$this->toCamelCase($key)} = $value;
}
}
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;
}
public function isPost()
{
return $this->requestMethod === "POST";
}
/**
* Implemented method
*/
public function getParams()
{
if ($this->requestMethod === "GET") {
$params = [];
foreach ($_GET as $key => $value) {
$params[$key] = filter_input(INPUT_POST, $key, FILTER_SANITIZE_SPECIAL_CHARS);
}
$this->params = array_merge($this->params, $params);
}
if ($this->requestMethod == "POST") {
$params = [];
foreach ($_POST as $key => $value) {
$params[$key] = filter_input(INPUT_POST, $key, FILTER_SANITIZE_SPECIAL_CHARS);
}
$this->params = array_merge($this->params, $params);
}
return $this->params;
}
}
This is how I would call the Router:
$router->get('/apply/{code}', function($request) use($myClass) {});
Which approach would be the better? I don't know how to resolve that.