rewrite/urls
< >

return function () {
    $self = url('/@object/@action/' . urlencode('rewrite/urls'));
    $demo = _class('docs')->_sample('rewrite_urls');
    $route = $demo->route($_GET['route'] ?? null);

    $intro = '<p class="docs-demo-intro">' . t('Pages are addressed as <code>?object=&action=&id=&page=</code>. With <code>$PROJECT_CONF[\'tpl\'][\'REWRITE_MODE\']</code> on (this site) <code>url()</code> builds short paths like <code>/object/action/id/page</code> and the router parses them back into the same <code>$_GET</code>; off, the same calls give the query form, so code and templates never write either form by hand. The table renders each call both ways (the setting is switched for the call only); the picker below runs fixed request paths through the parser of the yf pattern on a copy of the rewrite class. Read-only. Classes: <code>yf_rewrite</code>, <code>yf_rewrite_pattern_yf</code>.') . '</p>';

    $base = rtrim($demo->both(function () {
        return url('/');
    })['on'], '/');
    $link = function ($u) use ($base) {
        $u = (string) $u;
        if ($base !== '' && str_starts_with($u, $base)) {
            return '<span class="docs-demo-url-host">…</span>' . _prepare_html(substr($u, strlen($base)), 0, 0);
        }
        return _prepare_html($u, 0, 0);
    };

    $rows = '';
    foreach ($demo->calls() as $row) {
        $rows .= '<tr><td><code>' . _prepare_html($row['code'], 0, 0) . '</code></td><td class="docs-demo-url">' . $link($row['on']) . '</td><td class="docs-demo-url">' . $link($row['off']) . '</td></tr>';
    }
    $table = '<h3>' . t('url() in PHP') . '</h3><p>' . t('<code>url()</code> returns absolute links; their common start <code>%base</code> is shown as …', ['%base' => _prepare_html($base, 0, 0)]) . '</p><div class="table-responsive"><table class="table table-condensed table-sm table-striped docs-demo-urls">'
        . '<thead><tr><th>' . t('Call') . '</th><th>' . t('REWRITE_MODE on') . '</th><th>' . t('off') . '</th></tr></thead><tbody>' . $rows . '</tbody></table></div>'
        . '<p class="docs-demo-url-notes">' . t('An action of <code>show</code> is left out, a page without an id gets id <code>0</code>, other keys become the query string, <code>@object</code> / <code>@action</code> name the current page, <code>process_url()</code> rewrites a link written in the query form, admin links (<code>url_admin()</code>) always keep the query form. In templates the same calls are <code>{url(object=docs;action=install)}</code>, see <b>tpl/syntax</b>.') . '</p>';

    $links = '';
    foreach ($demo->ROUTES as $key => $path) {
        $links .= '<a class="btn btn-sm ' . ($key === $route ? 'btn-primary active' : 'btn-default btn-outline-primary') . '" href="' . $self . '?route=' . $key . '">' . _prepare_html($path, 0, 0) . '</a> ';
    }
    $get = $demo->parse($route);
    $back = $demo->both(function () use ($get) {
        return url($get);
    });
    $get_rows = '';
    foreach ($get as $k => $v) {
        $get_rows .= '<tr><th>' . _prepare_html((string) $k, 0, 0) . '</th><td>' . _prepare_html((string) $v, 0, 0) . '</td></tr>';
    }
    $html = _class('html');
    $parsed = '<h3>' . t('From a path to $_GET') . '</h3><p class="docs-demo-url-routes">' . $links . '</p>'
        . '<div class="' . $html->_ui_or('row', 'row') . '"><div class="' . $html->_ui_or('col-md-5', 'col', '5') . '"><h4>' . t('Request') . '</h4><p class="docs-demo-url"><code>' . _prepare_html($demo->ROUTES[$route], 0, 0) . '</code></p>'
        . '<h4>' . t('$_GET after routing') . '</h4><table class="table table-condensed table-sm docs-demo-url-get"><tbody>' . $get_rows . '</tbody></table></div>'
        . '<div class="' . $html->_ui_or('col-md-7', 'col', '7') . '"><h4>' . t('Back with url($_GET)') . '</h4><pre class="docs-demo-url-code"><code class="php">' . _prepare_html('url(' . $demo->export($get) . ')', 0, 0) . '</code></pre>'
        . '<table class="table table-condensed table-sm docs-demo-urls"><tbody><tr><th>' . t('REWRITE_MODE on') . '</th><td class="docs-demo-url">' . $link($back['on']) . '</td></tr>'
        . '<tr><th>' . t('off') . '</th><td class="docs-demo-url">' . $link($back['off']) . '</td></tr></tbody></table></div></div>'
        . '<p class="docs-demo-url-notes">' . t('Numbers after the object are an id (and a page), <code>/login</code> and <code>/logout</code> set <code>task</code>, an empty path opens <code>SITE_DEFAULT_PAGE</code>, and with <code>yf_rewrite::$QUERY_ROUTE_ON_EMPTY_PATH</code> (on here) <code>/?object=docs&action=install</code> routes like <code>/docs/install</code>. The router keeps only <code>a-z 0-9 _ -</code> in object and action.') . '</p>';

    css('.docs-demo-urls td, .docs-demo-urls th { vertical-align:top; }
        .docs-demo-urls td:first-child code { white-space:normal; word-break:break-word; }
        td.docs-demo-url, p.docs-demo-url { font-family:Menlo, Monaco, Consolas, "Courier New", monospace; font-size:13px; overflow-wrap:anywhere; }
        .docs-demo-urls tbody th { white-space:nowrap; font-weight:normal; width:1%; }
        .docs-demo-url-host { opacity:.55; }
        .docs-demo-url-get { width:auto; min-width:60%; }
        .docs-demo-url-get th { width:90px; font-weight:normal; color:#777; }
        .docs-demo-url-routes .btn { margin:0 4px 6px 0; font-family:Menlo, Monaco, Consolas, "Courier New", monospace; }
        section.page-contents pre.docs-demo-url-code { font-size:12px; }
        pre.docs-demo-url-code code { white-space:pre-wrap; word-break:break-word; }
        .docs-demo-url-notes { color:#666; }
        .cssfw-bs5 .docs-demo-url-notes, .cssfw-bs5 .docs-demo-url-get th { color:var(--bs-secondary-color); }');
    return $intro . $table . $parsed;
};

Сторінки адресуються як ?object=&action=&id=&page=. Коли $PROJECT_CONF['tpl']['REWRITE_MODE'] увімкнено (як на цьому сайті), url() будує короткі шляхи на кшталт /object/action/id/page, а маршрутизатор розбирає їх назад у той самий $_GET; коли вимкнено, ті самі виклики дають форму із запитом, тож код і шаблони ніколи не пишуть жодну з форм вручну. Таблиця рендерить кожен виклик обома способами (налаштування перемикається лише на час виклику); перемикач нижче проганяє фіксовані шляхи запитів через парсер шаблону yf на копії класу rewrite. Лише читання. Класи: yf_rewrite, yf_rewrite_pattern_yf.

url() у PHP

url() повертає абсолютні посилання; їхній спільний початок https://yfix.net показано як …

ВикликREWRITE_MODE увімкненовимкнено
url('/docs')…/uk/docs…/?object=docs&lang=uk
url('/docs/install')…/uk/docs/install…/?object=docs&action=install&lang=uk
url(['object' => 'docs', 'action' => 'install'])…/uk/docs/install…/?object=docs&action=install&lang=uk
url(['object' => 'news', 'action' => 'show', 'id' => 42])…/news/42…/?object=news&action=show&id=42
url(['object' => 'shop', 'action' => 'products', 'id' => 7, 'page' => 3])…/shop/products/7/3…/?object=shop&action=products&id=7&page=3
url(['object' => 'shop', 'page' => 2])…/shop/0/2…/?object=shop&page=2
url('/shop/search', ['q' => 'shoes', 'sort' => 'price'])…/shop/search?q=shoes&sort=price…/?object=shop&action=search&q=shoes&sort=price
url('/docs/install#requirements')…/uk/docs/install#requirements…/?object=docs&action=install&lang=uk#requirements
url(['task' => 'login'])…/login…/?task=login
url('/@object/@action')…/uk/docs/demo…/?object=docs&action=demo&lang=uk
process_url('./?object=docs&action=install')…/uk/docs/install…/?object=docs&action=install&lang=uk

Дія show пропускається, сторінка без id отримує id 0, інші ключі стають рядком запиту, @object / @action означають поточну сторінку, process_url() переписує посилання, написане у формі із запитом, а посилання адмінки (url_admin()) завжди зберігають форму із запитом. У шаблонах ті самі виклики — це {url(object=docs;action=install)}, див. tpl/syntax.

Від шляху до $_GET

/ /docs /docs/install /docs/demo/tpl%2Fsyntax /news/42 /shop/products/7/3 /shop/0/2 /shop/search?q=shoes&sort=price /login /?object=docs&action=install

Запит

/?object=docs&action=install

$_GET після маршрутизації

objectdocs
actionshow

Назад через url($_GET)

url(['object' => 'docs', 'action' => 'show'])
REWRITE_MODE увімкнено…/uk/docs
вимкнено…/?object=docs&action=show&lang=uk

Числа після об'єкта — це id (і сторінка), /login і /logout задають task, порожній шлях відкриває SITE_DEFAULT_PAGE, а з yf_rewrite::$QUERY_ROUTE_ON_EMPTY_PATH (тут увімкнено) /?object=docs&action=install маршрутизується як /docs/install. Маршрутизатор лишає в object і action лише a-z 0-9 _ -.