92 lines
1.7 KiB
PHP
Executable File
92 lines
1.7 KiB
PHP
Executable File
<?php
|
|
/*************************************************/
|
|
/* Classe de gestion des routes (URL/ressources) */
|
|
/*************************************************/
|
|
|
|
namespace router\core;
|
|
|
|
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
|
|
$this->routes = [
|
|
'GET' => [],
|
|
'POST' => []
|
|
];
|
|
|
|
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;
|
|
}
|
|
}
|
|
|
|
?>
|