I
I
Ivan Vasilich2020-04-20 12:16:54
PHP
Ivan Vasilich, 2020-04-20 12:16:54

Why is the method executed twice?

Good afternoon experts, tell me why my method is executed twice?

code in index

// --- Перманентные пути нужны для исполнения на любой странице

$permRoutes = array(

  '/authAction'  	=> 'UserIdentificator/authAction',
  '/online'		=> 'Visitor/users_online'
);

$res = array();

Routing::addRoute($permRoutes);

foreach ($permRoutes as $key => $value) {
  
  $res[$key] = Routing::dispatch($key);
  Routing::cleanRoutes($key);
}

print_r($res);

//echo 'Кол-во пользователей на сайте: '.$res['/online']['result'];

Routing::showRoutes();

// ----------------

$routes = array(
  //'/'						=> 'UserIdentificator/testing/helloworld',  // test
  //'/usersonline'			=> 'Visitor/getOnlineUsers', // выводит uagent всех пользователей на сайте
  '/login' 				=> 'UserIdentificator/loginAction',
  '/register' 			=> 'UserIdentificator/regAction',
  '/restore' 				=> 'UserIdentificator/resAction',
  '/verifres' 			=> 'UserIdentificator/verifResAction',
  '/verifreg' 			=> 'UserIdentificator/verifRegAction',
  '/logout' 				=> 'UserIdentificator/logout/true/false',
);

Routing::addRoute($routes); // Добавляем пути
$result = Routing::dispatch(); 
Routing::showRoutes();


I’ll write the router right away, I comunized where here.

public static function dispatch($requestedUrl = null) {

    // Если URL не передан, берем его из REQUEST_URI
    if ($requestedUrl === null) {

      $cur = self::getCurrentUri();

      $requestedUrl = $cur == '/' ? '/' : urldecode(rtrim($cur, '/'));
    }

    self::$requestedUrl = $requestedUrl;

    // $requestedUrl замененно на $fpath

    $fpath = '/'.self::getRoutes($requestedUrl)[0];

    // если URL и маршрут полностью совпадают
    if (isset(self::$routes[$fpath])) { // $requestedUrl

      self::$params = self::splitUrl(self::$routes[$fpath]);  // $requestedUrl
      return self::executeAction();
    }

    foreach (self::$routes as $route => $uri) {

      // Заменяем wildcards на рег. выражения
      if (strpos($route, ':') !== false) {
        
        $route = str_replace(':any', '(.+)', str_replace(':num', '([0-9]+)', $route));
      }

      if (preg_match('#^'.$route.'$#', $fpath)) {  // $requestedUrl
        
        if (strpos($uri, '$') !== false && strpos($route, '(') !== false) {

          $uri = preg_replace('#^'.$route.'$#', $uri, $requestedUrl);
        }

        self::$params = self::splitUrl($uri); // ты мы разбиваем value роута на параметры и сохраняем

        break; // URL обработан!
      } 
    } 
    return self::executeAction();
  } 
  public static function executeAction() {

    $controller = isset(self::$params[0]) ? self::$params[0]: 'MainController';
    $action 	= isset(self::$params[1]) ? self::$params[1]: 'defaultMethod';
    $params 	= array_slice(self::$params, 2);

    $obj 		= new $controller();
    $cresult 	= call_user_func_array(array($obj, $action), $params);

    debugger($cresult, __METHOD__.' '.$controller.' - '.$action);

    $errors = null;

    if(method_exists($controller, 'getErrors')) {

      $errors = $obj->getErrors(); 
      // array_filter();
    }
    return array(
      'result'		=> $cresult,
      'errors' 		=> $errors
    );
  }


outputs something like this

метод АУТЕНТИФИКАЦИИ запущен!
Откуда запущенно: Routing::executeAction Visitor - users_online 
integer => 1
Кол-во пользователей на сайте: 1
Откуда запущенно: Routing::executeAction Visitor - users_online 
integer => 1
Откуда запущенно: Routing::showRoutes 
Array
(
    [/login] => string => UserIdentificator/loginAction
    [/register] => string => UserIdentificator/regAction
    [/restore] => string => UserIdentificator/resAction
    [/verifres] => string => UserIdentificator/verifResAction
    [/verifreg] => string => UserIdentificator/verifRegAction
    [/logout] => string => UserIdentificator/logout/true/false
)


the problem is that I specify the controller '/online' => 'Visitor/users_online' and it is launched via dispatch and then I destroy it, but for some reason it still displays where it comes from

public static function cleanRoutes(string $arraykey) {
    if (array_key_exists($arraykey, self::$routes)) {
      unset(self::$routes[$arraykey]);
    }
  }

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question