A
A
Andrey Titov2018-01-31 16:06:57
PHP
Andrey Titov, 2018-01-31 16:06:57

Why might a PHP function not work?

Why might the function not work matchRoute()?
Router.php

<?php
  class Router {
    
    protected static $routes = [];
    protected static $route = [];

    public static function add($regexp, $route = []) {
      self::$routes[$regexp] = $route;
    }

    public static function getRoutes() {
      return self::$routes;
    }

    public static function getRoute() {
      return self::$route;
    }

    public static function matchRoute($url) {
      foreach(self::$routes as $pattern => $route) {
        if($url == $pattern) {
          self::$route = $route;
          return true;
        }
      }
      return false;
    }
  }
?>

index.php
<?php
  $query = $_SERVER['REQUEST_URI'];

  require '../vendor/core/Router.php';
  require '../vendor/libs/functions.php';

  Router::add('posts/add', ['controller' => 'Posts', 'action' => 'add']);
  Router::add('posts/', ['controller' => 'Posts', 'action' => 'index']);
  Router::add('', ['controller' => 'Main', 'action' => 'index']);
  
  debug(Router::getRoutes());

  if(Router::matchRoute($query)) {
    debug(Router::getRoute());
  } else {
    echo '404';
  }
?>

Answer the question

In order to leave comments, you need to log in

3 answer(s)
O
OKyJIucT, 2018-01-31
@titov_andrei

The passed $url contains a url that is not in the self::$routes array. How do you call it, what do you pass, what is the content of self::$routes?

M
Max, 2018-01-31
@AloneCoder

Apparently it should be

public static function matchRoute($url) {
      foreach(self::$routes as $pattern => $route) {
        if (preg_match($pattern, $url, $matches)) {
          self::$route = $route;
          return true;
        }
      }
      return false;
}

V
Vyacheslav, 2018-01-31
@Firik67

1. Because an incorrect $url may be passed
2. Because self::$routes may contain incorrect data
3. Because
What do you mean "doesn't work"?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question