- Joined
- Jan 27, 2012
- Messages
- 382
- Reaction score
- 343
Hey Guys.
I coded a routing system to improve my skills. I didn't try to code it in OOP (because I'm a lazy fag)
How to use it:
I know that the return thing is not the best solution but I'm to lazy to change it atm.
Class-Code:
Maybe you can post some feedback!
I coded a routing system to improve my skills. I didn't try to code it in OOP (because I'm a lazy fag)
How to use it:
PHP:
<?php
error_reporting(E_ALL);
require_once 'Router.php';
$router = new Router();
$router->add('/test', function() {
echo 'You opened /test';
});
$router->add('/test/@int:id/@string:title', function($params) {
echo 'You opened /test/'.$params['id'].'/'.$params['title'];
});
if(!isset($_GET['p'])) {
$_GET['p'] = '/index';
}
$router->setRoute($_GET['p']);
$route = $router->checkRoutes();
if($route != 'NOT_FOUND') {
return $route;
}
I know that the return thing is not the best solution but I'm to lazy to change it atm.
Class-Code:
PHP:
<?php
class Router {
private $routes = [];
private $route = '/';
public function add($route, $handler) {
if (!$this->routeExists($route)) {
$this->routes[] = [$route, $handler];
}
}
public function routeExists($searchingRoute) {
foreach ($this->routes as $route) {
if ($route[0] == $searchingRoute) {
return true;
}
}
return false;
}
public function setRoute($route) {
$this->route = rtrim($route, '/');
}
public function checkRoutes() {
$router = [];
$currentRoute = 'NOT_FOUND';
foreach ($this->routes as $route) {
if ($route[0] == $this->route) {
$currentRoute = $route[1]();
return;
}
$explodedRoute = explode('/', $route[0]);
$currentRoute = explode('/', $this->route);
$foundIntegers = 0;
$foundStrings = 0;
$params = [];
if (count($explodedRoute) == count($currentRoute)) {
for ($i = 0; $i < count($explodedRoute); $i++) {
if (substr($explodedRoute[$i], 0, 1) == '@') {
$explodedArea = explode(':', $explodedRoute[$i]);
$type = str_replace('@', '', $explodedArea[0]);
if ($type == 'int' && ctype_digit($currentRoute[$i])) {
$params[$explodedArea[1]] = $currentRoute[$i];
$foundIntegers++;
}
if ($type == 'string' && !ctype_digit($currentRoute[$i])) {
$params[$explodedArea[1]] = $currentRoute[$i];
$foundStrings++;
}
if (substr_count($route[0], '@int:') == $foundIntegers && substr_count($route[0], '@string:') == $foundStrings) {
$currentRoute = $route[1]($params);
return;
}
}
}
}
}
return $currentRoute;
}
}
Maybe you can post some feedback!