2016-04-04 09:47:17 +00:00
|
|
|
<?php
|
|
|
|
/*************************************************/
|
|
|
|
/* Classe de gestion des routes (URL/ressources) */
|
|
|
|
/*************************************************/
|
|
|
|
|
2016-10-18 11:09:39 +00:00
|
|
|
namespace manager\router;
|
2016-04-04 09:47:17 +00:00
|
|
|
|
|
|
|
class Router{
|
|
|
|
// ATTRIBUTS
|
|
|
|
private $url;
|
|
|
|
private $routes;
|
|
|
|
|
|
|
|
/* Initialise le routeur
|
|
|
|
*
|
|
|
|
* @url<String> l'URL de la page courante
|
|
|
|
*
|
|
|
|
* @return this<Router> Retour de l'instance courante
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
public function __construct($url){
|
|
|
|
$this->url = $url;
|
|
|
|
|
|
|
|
// On initialise les routes
|
2016-09-12 16:04:53 +00:00
|
|
|
$this->routes = [
|
|
|
|
'GET' => [],
|
|
|
|
'POST' => []
|
|
|
|
];
|
2016-04-04 09:47:17 +00:00
|
|
|
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* Ajoute une route GET
|
|
|
|
*
|
|
|
|
* @pattern<String> le format de l'URL associe
|
|
|
|
* @callback<Function> function a appeler si l'URL correspond
|
|
|
|
*
|
|
|
|
* @return this<Router> Retour de l'instance courante
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
public function get($pattern, $callback){
|
|
|
|
array_push(
|
|
|
|
$this->routes['GET'],
|
|
|
|
new Route($pattern, $callback)
|
|
|
|
);
|
|
|
|
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/* Ajoute une route POST
|
|
|
|
*
|
|
|
|
* @pattern<String> le format de l'URL associe
|
|
|
|
* @callback<Function> function a appeler si l'URL correspond
|
|
|
|
*
|
|
|
|
* @return this<Router> Retour de l'instance courante
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
public function post($pattern, $callback){
|
|
|
|
array_push(
|
|
|
|
$this->routes['POST'],
|
|
|
|
new Route($pattern, $callback)
|
|
|
|
);
|
|
|
|
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* Demarre le routeur
|
|
|
|
*
|
|
|
|
* @return this Retour de l'instance courante
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
public function run(){
|
|
|
|
$httpMethod = $_SERVER['REQUEST_METHOD'];
|
|
|
|
|
|
|
|
// Si aucune route pour la methode courante -> false
|
|
|
|
if( count($this->routes[$httpMethod]) <= 0 )
|
|
|
|
return false;
|
|
|
|
|
|
|
|
// Pour chaque route
|
|
|
|
foreach($this->routes[$httpMethod] as $route){
|
|
|
|
// Si la route match
|
|
|
|
if( $route->match($this->url) )
|
|
|
|
return $route->call(); // On l'amorce
|
|
|
|
}
|
|
|
|
|
|
|
|
// Retourne false si erreur
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-05-27 08:39:39 +00:00
|
|
|
?>
|