@Jers124

Почему не происходит перенаправления на страницу с ошибкой 404?

В адресную строку вбиваю несуществующую страницу "mysite.ru/hjfdjhdiuiiud6"

Выходит следующее сообщение Warning: call_user_func_array() expects parameter 1 to be a valid callback, class 'MainController' does not have a method 'actionIndexhmain' in C:\OS\OSPanel\domains\kia.ru\components\Router.php on line 64

Почему так происходит? Помогите разобраться.

Файл Router.php
class Router
{
    private $routes;

    public function __construct()
    {
        $routesPath = ROOT.'/config/routes.php';
        $this->routes = include($routesPath);
    }

    // return request string

    private function getURI()
    {
        if (!empty($_SERVER['REQUEST_URI'])) {
            return trim($_SERVER['REQUEST_URI'], '/');
        }
    }

    public function run()
    {
        //Получить строку запросы
        $uri = $this->getURI();

        //Проверить наличие такого запроса в routes.php
        foreach ($this->routes as $uriPattern => $path) {
        
           // Сравниваем $uriPattern и $uri
            if (preg_match("~$uriPattern~", $uri)) {

                //Получаем внутренний путь из внешнего согласно правилу
                $internalRoute = preg_replace("~$uriPattern~", $path, $uri);


                //Определить какой контроллер и action обрабатывает запрос и параметры
                
                $segments = explode('/', $internalRoute);

                $controllerName = array_shift($segments) . 'Controller';
                $controllerName = ucfirst($controllerName);

                $actionName = 'action'.ucfirst(array_shift($segments));

                $parameters = $segments;
                // echo '<pre>';

                // print_r($parameters);

                // die;

                //Подключить файл класса контроллера
                $controllerFile = ROOT . '/controllers/' . 
                $controllerName . '.php';

                if (file_exists($controllerFile)) {
                    include_once($controllerFile);
                }


                //Создать объект, взывать метод (т.е. action)
                $controllerObject = new $controllerName;
                $result = call_user_func_array(array($controllerObject, $actionName), $parameters);
                
                if($result != null){
                    break;
                }
            } 
        }
    }
}


Файл routes
return array(
    'work' => 'work/view',
    'job/([0-9]+)' => 'job/getTest/$1',
    'decis/([0-9]+)' => 'decis/view/$1',
    'about' => 'about/index',
    '' => 'main/index'    
);


Файл .htaccess
AddDefaultCharset utf-8

RewriteEngine on
RewriteBase /
# php_flag display_errors off

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^(.*)$ index.php
ErrorDocument 404 /err404.html
  • Вопрос задан
  • 397 просмотров
Пригласить эксперта
Ответы на вопрос 2
colonel
@colonel
Разработчик PHP, Laravel
Перенаправление на 404 не происходит, потому что так настроен .htaccess, все вызовы идут на index.php
Ответ написан
Комментировать
Должен быть хэдэр как минимум c ответом 404.
А для отображения страницы в роутах метод с выводом шаблона ошибки.
$route->onHttpError(
            function ($code) {
                $instance = "frontend\\controllers\\Home";
                switch ($code) {
                    case 404:
                    case 405:
                        header("HTTP/1.1 404 Not Found");
                        call_user_func([new $instance, "error404"], self::$answer[0][1]);
                        break;
                    case 403:
                        header("HTTP/1.1 403 Forbidden");
                        call_user_func([new $instance, "error403"], self::$answer[0][1]);
                        break;
                }
        }
 );

https://github.com/klein/klein.php
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
29 мар. 2024, в 15:28
10000 руб./за проект
29 мар. 2024, в 15:11
50000 руб./за проект
29 мар. 2024, в 15:06
50000 руб./за проект