Giter Club home page Giter Club logo

modxfastrouter's Introduction

MODX Fast Router

В основе MODX Fast Router используется замечательная библиотека https://github.com/nikic/FastRoute.

Основные особенности

  • Гибкая маршрутизация благодаря библиотеке nikic/FastRoute.
  • Ресурс или сниппет в качестве обработчика маршрута.
  • Простое создание и конфигурирование маршрутов.

Использование

Объявлять маршруты нужно в чанке fastrouter в таком формате:

[
    ["GET","/fastrouter/{name}/{id:[0-9]+}","1"],
    ["GET","/fastrouter/{id:[0-9]+}","1"],
    ["GET","/hello/{name}","1"],
    ["GET","/contact","1"],
    ["GET","/maybe-ajax-request","snippet_for_ajax_request"],
]
  • Первый параметр GET метод запроса, может быть GET, POST.
  • Второй параметр /fastrouter/{name}/{id:[0-9]+} наш маршрут, где {name} именованный параметр принимающий любые символы, {id:[0-9]+} именованный параметр принимающий только цифры. Можно использовать любые валидные регулярные выражения.
  • Третий параметр 2 ID ресурса куда будет направлен запрос или имя сниппета.

Если запрошенному URL не соответствует ни один объявленный маршрут, будет сгенерированна 404 ошибка.

Чтобы запрос не вошел в рекурсию при использовании в своих сниппетах и компонентах метода sendErrorPage, необходимо передать в метод array('stop' => true). Должно получится вот так:

$modx->sendErrorPage(array('stop' => true));

Если использовать в качестве обработчика ID ресурса, то все именованные параметры попадут в массив fastrouter в глобальном массиве $_REQUEST. В нашем случае по первому маршруту, например http://site.com/fastrouter/vanchelo/10 получим вот такие данные:

var_dump($_REQUEST);

Array
(
    [q] => user/vanchelo/10
    [fastrouter] => Array
        (
            [name] => vanchelo
            [id] => 10
        )
)

В случае, если обработчиком является сниппет, все параметры будут доступны в $scriptProperties, получить их можно будет таким образом:

$key = $modx->getOption('fastrouter.paramsKey', null, 'fastrouter');
$params = $modx->getOption($key, $scriptProperties, array());

return '<pre>' . print_r($params, true) . '</pre>';

По умолчанию имя ключа со всеми параметрами маршрута - fastrouter. Для задания своего ключа измените в настройках системы параметр fastrouter.paramsKey.

Скачать готовый пакет здесь fastrouter-1.0.4-pl.transport.zip Или последний релиз с GitHub https://github.com/vanchelo/modxFastRouter/releases

modxfastrouter's People

Contributors

vanchelo avatar russelgal avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.