L
L
leni_m2017-10-16 18:09:15
PHP
leni_m, 2017-10-16 18:09:15

MVC routing in php?

Hello toasters!
I have a simple MVC implementation
here is the router:

<?php

class Router
{
    private $routes;

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

    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'; //array_shift выбирает 1-ый елемент и уничтожает его
                $controllerName = ucfirst($controllerName);

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

                $parameters = $segments; //т.к. после 2-ух array_shift останутся одни параметры, они сюда и запишутся

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

                $internalRoute = preg_replace("~$uriPattern~", $path, $uri);



                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.php stores paths of the type "products" => "site/products",
and it turns out that the function will work at the address domen.ru/products
public static function actionProducts()
{
...
return true;
}

in the SiteController.php class
And here the problem is that if you write a url different from those in routes.php, then the following error occurs: "Warning: call_user_func_array() expects parameter 1 to be a valid callback, class 'SiteController' does not have a method 'action..."
I don't know how to implement that if there is no such address in routes.php, then a 404 page would be displayed for example. Or execute some code if there is no such address in routes.php
How to be here?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
ThunderCat, 2019-07-15
@ThunderCat

Firstly

dataType: "json", // data transfer type
it is not a transfer type, but the data type of the expected response. That is, json should arrive in response.
Secondly:
but die doesn't work.. WHY? It works on any other page, but not here ... maybe because ajax sent data here? TELL ME PLEASE)))))
die works, it's just that you don't understand what you're doing, and that makes you crap. The server returns a string to the SCRIPT, which, apart from the fact that nothing is in json, is not yet "added" to the html, but is returned to the script as a return variable. Look in the browser console - there should be a corresponding error, and in the network tab there should also be a response body.
Specifically, in your case, it seems that part of the script was written by someone else who understands something, and you stuck your die with left nonsense.

D
Dmitry Dart, 2017-10-16
@leni_m

Just take a klein router or aura router, take it all apart, see what goes where, how why, and everything will become clear to you.
And another OOP router != MVC application. You can put a cool router and then nagovnokodit.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question