I was trying to keep it SRP. I'm new into PHP OOP and I'm wondering how I can make it better.
Route.php
class Route
{
private $_url;
private $_callback;
private $_name;
public function __construct($_url, $callback)
{
$this->_url = '/^' . str_replace('/', '\\/', $_url) . '$/';
if (is_callable($callback)) {
$this->_callback = $callback;
return;
}
if (is_string($callback)
&& substr_count($callback, '@') == 1
&& file_exists(CONTROLLER_PATH . '/' . explode('@', $callback)[0] . '.php')) {
$this->_callback = explode('@', $callback);
require_once CONTROLLER_PATH . '/' . $this->_callback[0] . '.php';
$this->_callback[0] = new $this->_callback[0];
return;
}
exit('Error!');
}
public function getURL()
{
return $this->_url;
}
public function getCallback()
{
return $this->_callback;
}
}
Router.php
<?php
class Router
{
const GET = 'GET';
const POST = 'POST';
private static $_routes = array(
'GET' => array(),
'POST' => array()
);
public static function add(Route $route, $method)
{
switch ($method) {
case 'GET':
self::$_routes['GET'][$route->getURL()] = $route->getCallback();
break;
case 'POST':
self::$_routes['POST'][$route->getURL()] = $route->getCallback();
break;
default:
exit('Error!');
break;
}
}
public static function get(Route $route)
{
self::add($route, self::GET);
}
public static function post(Route $route)
{
self::add($route, self::POST);
}
public static function run()
{
$path = array_key_exists('path', $_GET) ? '/' . $_GET['path'] : '/';
foreach (self::$_routes[$_SERVER['REQUEST_METHOD']] as $url => $callback) {
if (preg_match($url, $path, $matches)) {
array_shift($matches);
call_user_func_array($callback, array_values($matches));
return;
}
}
}
}
controller/HomeController.php
<?php
class HomeController
{
public function index()
{
echo 'Hello World!'
}
}
Using example
<?php
Router::get(new Route('/', 'HomeController@index'));
Router::run();
?>
if
block taken out of context. See how to get the best value out of Code Review on meta for more info. – Mat's Mug♦ Feb 20 at 2:28