Je reçois l'erreur suivante :

Code de l'index.php

<?php
require 'vendor/autoload.php';

$router = new Library\Router\Router($_GET['url']);
$router->post('/login', function(){ require 'test.php'; });

$router->run();

Code router :

 private $url;
    private $routes = [];
    private $namedRoutes = [];

    public function __construct($url){
        $this->url = $url;
    }

    public function get($path, $callable, $name = null){
        return $this->add($path, $callable, $name, 'GET');
    }

    public function post($path, $callable, $name = null){
        return $this->add($path, $callable, $name, 'POST');
    }

    private function add($path, $callable, $name, $method){
        $route = new Route($path, $callable);
        $this->routes[$method][] = $route;
        if(is_string($callable) && $name === null){
            $name = $callable;
        }
        if($name){
            $this->namedRoutes[$name] = $route;
        }
        return $route;
    }

    public function run(){
        if(!isset($this->routes[$_SERVER['REQUEST_METHOD']])){
            throw new RouterException('REQUEST_METHOD does not exist');
        }
        foreach($this->routes[$_SERVER['REQUEST_METHOD']] as $route){
            if($route->match($this->url)){
                return $route->call();
            }
        }
        throw new RouterException('No matching routes');
    }

    public function url($name, $params = []){
        if(!isset($this->namedRoutes[$name])){
            throw new RouterException('No route matches this name');
        }
        return $this->namedRoutes[$name]->getUrl($params);
    }

Code route.php

private $path;
    private $callable;
    private $matches = [];
    private $params = [];

    public function __construct($path, $callable){
        $this->path = trim($path, '/');
        $this->callable = $callable;
    }

    public function with($param, $regex){
        $this->params[$param] = str_replace('(', '(?:', $regex);
        return $this;
    }

    public function match($url){
        $url = trim($url, '/');
        $path = preg_replace_callback('#:([\w]+)#', [$this, 'paramMatch'], $this->path);
        $regex = "#^$path$#i";
        if(!preg_match($regex, $url, $matches)){
            return false;
        }
        array_shift($matches);
        $this->matches = $matches;
        return true;
    }

    private function paramMatch($match){
        if(isset($this->params[$match[1]])){
            return '(' . $this->params[$match[1]] . ')';
        }
        return '([^/]+)';
    }

    public function call(){
        if(is_string($this->callable)){
            $params = explode('#', $this->callable);
            $controller = "Library\\Controller\\" . $params[0] . "Controller";
            $controller = new $controller();
            return call_user_func_array([$controller, $params[1]], $this->matches);
        } else {
            return call_user_func_array($this->callable, $this->matches);
        }
    }

    public function getUrl($params){
        $path = $this->path;
        foreach($params as $k => $v){
            $path = str_replace(":$k", $v, $path);
        }
        return $path;
    }

8 réponses


Arnaud Mcho Scott
Réponse acceptée

Bonjour,

Il faut que tu renseigne ta route en tant que get et non post.

$router->get('/login', function(){ require 'test.php'; });

Voici une bonne explication entre les méthodes POST et GET :

In computing, POST is one of many request methods supported by the HTTP protocol used by the World Wide Web. By design, the POST request method requests that a web server accepts and stores the data enclosed in the body of the request message.[1] It is often used when uploading a file or submitting a completed web form.

In contrast, the HTTP GET request method is designed to retrieve information from the server. As part of a GET request, some data can be passed within the URL's query string, specifying for example search terms, date ranges, or other information that defines the query. As part of a POST request, an arbitrary amount of data of any type can be sent to the server in the body of the request message. A header field in the POST request usually indicates the message body's Internet media type.

Si j'ai bien compris ,l'erreur vient de là

if(!isset($this->routes[$_SERVER['REQUEST_METHOD']])){
            throw new RouterException('REQUEST_METHOD does not exist');
        }

la variable $this->routes est un tableau qui contient les routes groupées par méthode
peut être faut-il créer les entrées 'GET' et 'POST' à la main
essaye de voir la méthode demandée

if(!isset($this->routes[$_SERVER['REQUEST_METHOD']])){
            throw new RouterException('REQUEST_METHOD does not exist : ' . $_SERVER['REQUEST_METHOD'] );
        }

J'ai fait ce que tu ma dis voila l'erreur que j'ai maintenant

Tes routes ne sont pas chargées
ton tableau $this->routes doit être vide non ? ou alors il n'y a aucune route de méthode POST

j'ai fais la condition suivante

if(!isset($this->routes[$_SERVER['REQUEST_METHOD']]))
        {
            $test = $_SERVER['REQUEST_METHOD'];
        }
        else
        {
            $test = 'non';
        }

Et sa me mais "non" pour tant quand je fais un return de $this->routes; j'ai bien la méthode post qui s'affiche

Logique, la route existe donc il fait le else.

D'aprés ce que j'ai compris en regardant le code et faisant des essaie j'apelle la méthode post mais cela ne marche pas car ma page est en méthod get comment je pourais faire.