我正在尝试创建一个将“覆盖”此类 URL 的路由:
www.test.com/parent1/parent2/parent3/item
www.test.com/parent1/parent2/parent3/parent4/item1
未指定的父级数量,它应该只用于为站点 URL 提供更好、更直观的外观。主要参数是“项目”。
我想解决这个问题的唯一方法是使用 Route_Regex,所以我试图用这样的东西来完成这个路由任务:
routes.test.type = "Zend_Controller_Router_Route_Regex"
routes.test.route = "test/(?:.*)?([^\/]+)"
routes.test.defaults.module = default
routes.test.defaults.controller = test
routes.test.defaults.action = index
routes.test.map.1 = "path"
routes.test.map.2 = "item"
routes.test.reverse = "test/%s%s"
我没有对此进行过多测试,因为我不确定我是否在做正确的事情......我不知道那个正则表达式应该是什么样子,以及我应该如何对待那个“路径”。
你能建议我应该怎么做才能满足这种路线需求吗?因此,我只需要该路径(parent1、parent2 等)仅用于外观,而主要参数是“项目”...
最佳答案
我知道这是一个老问题,但我有一个类似的问题,只是想我应该发布我的解决方案。也许它可以帮助其他人查看这个问题。
我在插件中编写了我的路由,显然你需要将插件添加到 bootstrap 中才能工作;)
class Plugin_RoutesPage extends Zend_Controller_Plugin_Abstract
{
public function routeStartup(Zend_Controller_Request_Abstract $request)
{
$front_controller = Zend_Controller_Front::getInstance();
$router = $front_controller->getRouter();
// Page SEO friendly hierarchical urls
$routePageSeoTree = new Zend_Controller_Router_Route_Regex(
'([-a-zA-Z0-9/]+)/([-a-zA-Z0-9]+)',
array(
// default Route Values
'controller' => 'page',
'action' => 'open',
),
array(
// regex matched set names
1 => 'parents',
2 => 'item'
)
);
$router->addRoute('page-seo-tree',$routePageSeoTree);
// only one level
$routeSinglePage = new Zend_Controller_Router_Route_Regex(
'([-a-zA-Z0-9]+)',
array(
// default Route Values
'controller' => 'page',
'action' => 'open',
),
array(
// regex matched set names
1 => 'item'
)
);
$router->addRoute('page-single',$routeSinglePage);
}
}
这是您可以在 Controller 的操作中使用它的方式
class PageController extends Zend_Controller_Action
{
public function openAction()
{
// the part of the uri that you are interested in
$item = $this->_request->getParam('item');
}
}
这是如何将其包含到 bootstrap 中的快速示例
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initPlugins()
{
$front_controller = Zend_Controller_Front::getInstance();
$front_controller->registerPlugin(new Plugin_RoutesPage(), 1);
}
}
我不得不使用两条路线,因为我们试图查看/打开的当前页面可能没有任何父页面。我确信可能有更好的方法来编写正则表达式,但这对我有用。如果有人知道如何改进正则表达式,请告诉我。
关于regex - Zend Route Url 与正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1655492/