Как я могу сократить определение моих пользовательских маршрутов в Zend Framework? В настоящее время у меня это определение:
$route = new Zend_Controller_Router_Route( ":module/:id", array( "controller" => "index", "action" => "index" ), array("id" => "\d+") ); self::$frontController->getRouter()->addRoute('shortcutOne', $route); $route = new Zend_Controller_Router_Route( ":module/:controller/:id", array("action" => "index"), array("id" => "\d+") ); self::$frontController->getRouter()->addRoute('shortcutTwo', $route); $route = new Zend_Controller_Router_Route( ":module/:controller/:action/:id", null, array("id" => "\d+") ); self::$frontController->getRouter()->addRoute('shortcutThree', $route);
Есть ли способ лучше совместить эти правила? И каковы ваши лучшие практики в том, где их разместить? В настоящее время я имею их в своем классе начальной загрузки сразу после инициализации Front Controller.
Когда дело доходит до настройки таких маршрутов, я использую конфигурационный файл. В качестве предпочтения я использую XML для хранения моих данных конфигурации, однако их можно так же легко сохранить в другом поддерживаемом формате. Затем я добавляю маршруты из конфига, в маршрутизатор в моем бутстрапе.
Config:
<config> <routes> <shortcutone type="Zend_Controller_Router_Route"> <route>:module/:id</route> <defaults> <controller>index</controller> <action>index</action> </defaults> <reqs id="\d+"> </shortcutone> <shortcuttwo type="Zend_Controller_Router_Route"> <route>:module/:controller/:id</route> <defaults> <controller>index</controller> </defaults> <reqs id="\d+"> </shortcuttwo> <shortcutthree type="Zend_Controller_Router_Route"> <route>:module/:controller/:action/:id</route> <defaults> <controller>index</controller> <action>index</action> </defaults> <reqs id="\d+"> </shortcutthree> </routes> </config>по<config> <routes> <shortcutone type="Zend_Controller_Router_Route"> <route>:module/:id</route> <defaults> <controller>index</controller> <action>index</action> </defaults> <reqs id="\d+"> </shortcutone> <shortcuttwo type="Zend_Controller_Router_Route"> <route>:module/:controller/:id</route> <defaults> <controller>index</controller> </defaults> <reqs id="\d+"> </shortcuttwo> <shortcutthree type="Zend_Controller_Router_Route"> <route>:module/:controller/:action/:id</route> <defaults> <controller>index</controller> <action>index</action> </defaults> <reqs id="\d+"> </shortcutthree> </routes> </config>по<config> <routes> <shortcutone type="Zend_Controller_Router_Route"> <route>:module/:id</route> <defaults> <controller>index</controller> <action>index</action> </defaults> <reqs id="\d+"> </shortcutone> <shortcuttwo type="Zend_Controller_Router_Route"> <route>:module/:controller/:id</route> <defaults> <controller>index</controller> </defaults> <reqs id="\d+"> </shortcuttwo> <shortcutthree type="Zend_Controller_Router_Route"> <route>:module/:controller/:action/:id</route> <defaults> <controller>index</controller> <action>index</action> </defaults> <reqs id="\d+"> </shortcutthree> </routes> </config>по<config> <routes> <shortcutone type="Zend_Controller_Router_Route"> <route>:module/:id</route> <defaults> <controller>index</controller> <action>index</action> </defaults> <reqs id="\d+"> </shortcutone> <shortcuttwo type="Zend_Controller_Router_Route"> <route>:module/:controller/:id</route> <defaults> <controller>index</controller> </defaults> <reqs id="\d+"> </shortcuttwo> <shortcutthree type="Zend_Controller_Router_Route"> <route>:module/:controller/:action/:id</route> <defaults> <controller>index</controller> <action>index</action> </defaults> <reqs id="\d+"> </shortcutthree> </routes> </config>по<config> <routes> <shortcutone type="Zend_Controller_Router_Route"> <route>:module/:id</route> <defaults> <controller>index</controller> <action>index</action> </defaults> <reqs id="\d+"> </shortcutone> <shortcuttwo type="Zend_Controller_Router_Route"> <route>:module/:controller/:id</route> <defaults> <controller>index</controller> </defaults> <reqs id="\d+"> </shortcuttwo> <shortcutthree type="Zend_Controller_Router_Route"> <route>:module/:controller/:action/:id</route> <defaults> <controller>index</controller> <action>index</action> </defaults> <reqs id="\d+"> </shortcutthree> </routes> </config>по<config> <routes> <shortcutone type="Zend_Controller_Router_Route"> <route>:module/:id</route> <defaults> <controller>index</controller> <action>index</action> </defaults> <reqs id="\d+"> </shortcutone> <shortcuttwo type="Zend_Controller_Router_Route"> <route>:module/:controller/:id</route> <defaults> <controller>index</controller> </defaults> <reqs id="\d+"> </shortcuttwo> <shortcutthree type="Zend_Controller_Router_Route"> <route>:module/:controller/:action/:id</route> <defaults> <controller>index</controller> <action>index</action> </defaults> <reqs id="\d+"> </shortcutthree> </routes> </config>по<config> <routes> <shortcutone type="Zend_Controller_Router_Route"> <route>:module/:id</route> <defaults> <controller>index</controller> <action>index</action> </defaults> <reqs id="\d+"> </shortcutone> <shortcuttwo type="Zend_Controller_Router_Route"> <route>:module/:controller/:id</route> <defaults> <controller>index</controller> </defaults> <reqs id="\d+"> </shortcuttwo> <shortcutthree type="Zend_Controller_Router_Route"> <route>:module/:controller/:action/:id</route> <defaults> <controller>index</controller> <action>index</action> </defaults> <reqs id="\d+"> </shortcutthree> </routes> </config>
начальная загрузка
$config = new Zend_Config_Xml('config.xml'); $router = Zend_Controller_Front::getInstance()->getRouter(); $router->addConfig($config, 'routes');
Очевидно, есть другие варианты, и я бы рекомендовал вам прочитать документацию по этому вопросу, однако это подходит для вашего примера.
Мой файл routes.ini начал получать очень большой, поэтому я решил использовать Zend Caching для кэширования маршрутов после их анализа. Я использовал Xcache для решения кэширования бэкэнд. Вот код, который нужно поместить в файл Bootstrap.php:
защищенная функция _initRoutes ()
{
$ backendType = 'Xcache';
$ backendOptions = array ();
// Создание объекта кэширования для кэширования маршрутов
$ cache = Zend_Cache :: factory ('Файл', $ backendType,
массив (
'automatic_serialization' => true,
'master_files' => array (APPLICATION_PATH. '/configs/routes.ini)
),
$ backendOptions
);
$ frontController = Zend_Controller_Front :: getInstance ();
if (! $ router = $ cache-> load ('router')) {
// Загрузите файл .ini и поместите результаты в кеш
$ routes = new Zend_Config_Ini (APPLICATION_PATH. '/configs/routes.ini', 'production');
$ router = $ frontController-> getRouter ();
$ router-> addConfig ($ routes, 'routes');
$ cache-> save ($ router, 'router');
}
else {
// Использовать кешированную версию
$ FrontController-> setRouter ($ маршрутизатор);
}
}
Я предпочитаю использовать * .ini файлы по XML, особенно при использовании Zend, поскольку он более Zend-подобный и гораздо более легкий и компактный. Вот почти аналогичная конфигурация с помощью Zend_Config_Ini() .
application.ini
[routes] routes.shortcutone.route=:module/:id routes.shortcutone.defaults.controller=index routes.shortcutone.defaults.action=index routes.shortcutone.reqs=\d+
bootstrap.php
$config = new Zend_Config_Ini('application.ini', 'routes'); $router = Zend_Controller_Front::getInstance()->getRouter(); $router->addConfig($config, 'routes');
Обратите внимание, что раздел [routes] в файле application.ini можно переименовать. И когда он будет переименован, второй параметр Zend_Config_Ini() должен отражать заголовок нового раздела.