V
V
Valentin Shapkin2016-04-15 22:56:17
CMS
Valentin Shapkin, 2016-04-15 22:56:17

What is the essence of the router in php?

I know and am well-read about such similar questions as mine, but still I would like more detailed explanations. The only thing I understood is that the router in the engines for sites work with url addresses, parse them and set some kind of module there to display the page, etc.
1. What is the essence of the router as a whole?
2. Is it needed at all?
3. Give a small example (preferably on functions) of a router.
4. Can I do without it?
I want to develop my own router referring to the experience of existing developments.
Ps I am developing my mini engine for my personal website (like a blog).

Answer the question

In order to leave comments, you need to log in

4 answer(s)
I
Igor Makarov, 2016-04-16
@smart_pro

1. Here they scare with all sorts of controllers, laravel. Let's live easier. First, let's define the buzzword router. This is a router . What does a router do? Correctly. Processes routes, being a connecting link. The route for a web site is considered to be the request method [ GET, POST, PUT и другие] and URI components.

например: https://ru.wikipedia.org/wiki/URI?foo=bar#title
[схема: https] :// [источник: ru.wikipedia.org] [путь: /wiki/URI] [запрос: ?foo=bar] [фрагмент: #title]

But to determine the route, any other information transmitted to the server can be taken, the definition above is only the most used parameters.
The work itself is usually simple: a request comes from the client, the router goes through all the paths given to it until the first match. On a match, the function you defined is called and returns a response to the client.
2. It is necessary if the application has one entry point, when any request comes for one file.
3. A simple example
// файл index.php

// Маршруты
// [маршрут => функция которая будет вызвана]
$routes = [
    // срабатывает при вызове корня или /index.php
    '/' => 'hello',
    // срабатывает при вызове /about или /index.php/about
    '/about' => 'about',
    // динамические страницы
    '/page' => 'page'
];

// возвращает путь запроса
// вырезает index.php из пути
function getRequestPath() {
    $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

    return '/' . ltrim(str_replace('index.php', '', $path), '/');
}

// наш роутер, в который передаются маршруты и запрашиваемый путь
// возвращает функцию если маршшрут совпал с путем
// иначе возвращает функцию notFound
function getMethod(array $routes, $path) {
    // перебор всех маршрутов
    foreach ($routes as $route => $method) {
        // если маршрут сопадает с путем, возвращаем функцию
        if ($path === $route) {
            return $method;
        }
    }

    return 'notFound';
}

// функция для корня
function hello() {
    return 'Hello, world!';
}

// функция для страницы "/about"
function about() {
    return 'About us.';
}

// чуть более сложный пример
// функция отобразит страницу только если
// в запросе приходит id и этот id равен
// 33 или 54
// [/page?id=33]
function page() {

    $pages = [
        33 => 'Сага о хомячках',
        54 => 'Мыши в тумане'
    ];

    if (isset($_GET['id']) && isset($pages[$_GET['id']])) {
        return $pages[$_GET['id']];
    }

    return notFound();
}

// метод, который отдает заголовок и содержание для маршрутов,
// которые не существуют
function notFound() {
    header("HTTP/1.0 404 Not Found");

    return 'Нет такой страницы';
}


// Роутер
// получаем путь запроса
$path = getRequestPath();
// получаем функцию обработчик
$method = getMethod($routes, $path);
// отдаем данные клиенту
echo $method();

In practice , more complex routers are used, which have much greater capabilities.
4. You can do without it. If each page in your application will be a separate file that is responsible for the return of information.
index.php
about.php
contact.php
...

This is an old-school structure, almost never used in new projects.

A
Alexander Kubintsev, 2016-04-21
@akubintsev

Regarding point number 2. Without a router, the nginx/apache config will quickly grow into a kilometer-long sheet, and with each new line, the chance to break something will increase.

V
Vladimir Luchaninov, 2017-10-14
@how

Here is a detailed description of how framework approaches (including routers) differ from regular PHP
https://symfony.com.ua/doc/current/introduction/fr...
Symfony router documentation
https://symfony.com. ua/doc/current/routing.html

A
Alexey Leonov, 2020-08-19
@rip106

And why, when applying routing, they use exactly this approach
www.my.site/docs/writes/news?id=7
and not a set of GET parameters
www.my.site/index.php?docs=writes&news=7
After all, it’s shorter to check the existence of a get parameter (isset($_GET['X'])) than to parse the url and then check for the presence of a specific path in it.
What is the advantage of the first option?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question