使用Zend Framework中的Zend_Controller_Router_Route_Regex在参数中匹配多个URL

sha*_*nth 8 php zend-framework zend-route

我正在使用Zend开发一个Rest Controller,我对url到Router的映射感到困惑.

基本上我读了Zend路由器,我无法计划我的网址,以满足上述路线.

这些是我应该映射到路由器的一些网址.

  1. HTTP://localhost/api/v1/tags.xml

  2. http://localhost/api/v1/tags.xml?abc = true (param:abc = true)

  3. http://localhost/api/v1/tags/123456.xml (param:123456.xml)

  4. http://localhost/api/v1/tags/123456/pings.xml (参数:123456,pings.xml)

  5. http://localhost/api/v1/tags/123456/pings.xml?a = 1&b = 2(参数:123456,pings.xml,a = 1,b = 2)

  6. http://localhost/api/v1/tags/123456/pings/count.xml(参数:123456,ping,count.xml)

我正在计划,对于网址模式1到3,"标签"应该是控制器,对于网址模式4到6,"ping"应该是控制器.

现在我不确定如何配置路由器,以便上述方案可行.请注意,我无法更改这些网址.我可以提供100分的良好答案.

Len*_*ran 6

前两个URL可以组合到一个路由器.

$r = new Zend_Controller_Router_Route_Regex('api/v1/tags.xml',
                array('controller' => 'tags', 'action' => 'index'));
$router->addRoute('route1', $r);
Run Code Online (Sandbox Code Playgroud)

要区分前两个路由,请检查标记控制器中是否存在abc参数.在标记控制器中添加以下内容,索引操作.

if($this->_getParam('abc') == "true")
{
//route 2
} else {
// route 1
}
Run Code Online (Sandbox Code Playgroud)

类似地,路线4和5可以组合成一个路线.

我已经解释了Route 6.对于路由3,你可以使用相同的逻辑.

$r = new Zend_Controller_Router_Route_Regex('api/v1/tags/(.*)/pings/(.*)',
                array('controller' => 'pings', 'action' => 'index'),
array(1 => 'param1',2=>'param2')
);
$router->addRoute('route6', $r);
Run Code Online (Sandbox Code Playgroud)

然后可以在ping控制器中访问以下参数.

$this->_getParam('param1') and $this->_getParam('param2')
Run Code Online (Sandbox Code Playgroud)

对于5号公路:

$r = new Zend_Controller_Router_Route_Regex('api/v1/tags/(.*)/pings.xml',
                array('controller' => 'pings', 'action' => 'index'),
array(1 => 'param1')
);
$router->addRoute('route5', $r);
Run Code Online (Sandbox Code Playgroud)

路由器不会处理参数(后面的URL的一部分?).默认情况下,它们将传递给您的控制器.

要获取URL中传递的特定参数值,请在控制器中使用以下命令.

$this->_getParam('a');
Run Code Online (Sandbox Code Playgroud)

逻辑是在您的路由中使用(.*)并为它们分配参数名称并在您的控制器中访问它们