php: simple router implementation

Trabla: php: simple router implementation example

Solving:

<?php

class Router{


const GET = 'GET';
const POST = 'POST';

private $appRoot; 
private $routes;
private $default = null; 

public $action = null;

const EXCEPTION_WRONG_CONFIG = 'Error config is not object';

private $config;

public function __construct( ){

$this->routes = array( 
self::GET => array(),
self::POST => array()
);


}


private function addRoute( $method, $params, $callback ){

$route = new Route( $method, $params );

array_push( $this->routes[ $method ] , array(
'route' => $route,
'callback' => $callback
));

}

public function setDefault( $callback ){
$this->default = $callback;
}

private function getRequestParams( $method ){
if( $method == self::GET ){
return $_GET;
}
else if( $method == self::POST ){
return $_POST;
}else{
throw new Exception( 'Error Inncorect Request Method' );
}
}


public function get( $params, $callback ){
$this->addRoute( self::GET, $params, $callback );
}

public function post( $params, $callback ){
$this->addRoute( self::POST, $params, $callback );
}

public function run(){

$method = $_SERVER['REQUEST_METHOD'];
$params =   $this->getRequestParams($method);
$default =  $this->default;

$routeNotFound = true;

foreach( $this->routes[$method] as &$route ){

if( $route['route']->isValid( $method, $params ) ){
$route['callback']($params);
$routeNotFound = false;
break;
}

}
unset($route);

if( $routeNotFound == true && count($params) > 0){
echo 'Route Not Found';
}

if( $routeNotFound == true && count($params) == 0){
echo $default();
}

}

}

class Route{

const EXCEPTION_PARAMS_MUST_BE_ARRAY = 'Error "params" must be array';

private $params = array();
private $method = '';

public function __construct( $method, $params ){

if(!is_array($params)){
throw new Exception( self::EXCEPTION_PARAMS_MUST_BE_ARRAY );
}

$this->method = $method;
$this->params = $params;


}

public function isValid( $method, $params ){

$valid = true;

if(!is_array($params)){
throw new Exception( self::EXCEPTION_PARAMS_MUST_BE_ARRAY );
}

if( $this->method != $method ){
return false;
}

foreach( $this->params as &$key) {
$valid = $valid && array_key_exists( $key,  $params );
}
unset($key);

return $valid;

}
}

?>

Quick start:

1. Create file Router.php in your web dir and copy code above
/var/www/test/Router.php

2. Create index.php with code
/var/www/test/index.php

<?php

//Change to your path
require_once '/var/www/test/Router.php' ;


$app = new Router();

//Home
$app->setDefault( function(){
echo 'Home page';
});

//GET request
$app->get( array('user','format') , function( $params ) {
echo 'Hello user:' . $params['user'];
});

//POST request
$app->post( array('controller', 'action') , function( $params ) {
echo 'Controller:' . $params['controller'] . ' action: ' . $params['action'];
});


$app->run();

?>





No comments:

Post a Comment