如何使用Zend_Controlle链接多个路由

时间:2011-11-03 07:19:52

标签: php zend-framework router chain undefined-index

我的问题是如何使用Zend_Controller_Router_Route_Chain链接多个路由?

例如,我想链接3条路线,每年/每月/每天 但是gole是:

when url is
example.com/2011
runs index controller, year action

example.com/2011/11
runs index controller, year-month action

example.com/2011/11/10
runs index controller, year-month-day action

我正在尝试使用此代码:

$front = Zend_Controller_Front::getInstance();
$router = $front->getRouter();
$chain = new Zend_Controller_Router_Route_Chain();

$route1 = new Zend_Controller_Router_Route(
    ':year',
    array(
        'controller' => 'news',
        'action'     => 'year'
    )
);

$route2 = new Zend_Controller_Router_Route(
    ':month',
    array(
        'controller' => 'news',
        'action'     => 'year-month'
    )
);

$route3 = new Zend_Controller_Router_Route(
    ':day',
    array(
        'controller' => 'news',
        'action'     => 'year-month-day'
    )
);

$chain->chain($route1)
      ->chain($route2)
      ->chain($route3);

$router->addRoute('chain', $chain)
       ->addRoute('route3', $route3)
       ->addRoute('route2', $route2)
       ->addRoute('route1', $route1);

当我转到example.com/2012和example.com/2012/11/11时一切正常

但是当我访问example.com/2012/11/应用程序显示我的年月日行动时,页面上有

Notice: Undefined index: day in P:\Zend\ZendServer\share\ZendFramework\library\Zend\Controller\Router\Route.php on line 299

也许我做错了什么。拜托,帮我解决我的问题。感谢。

1 个答案:

答案 0 :(得分:0)

嗯,显示“未定义的索引”通知,因为您没有为路由器提供年,月,日的任何默认值。

解决方案的一个想法是仅使用一个路由来匹配每个请求,使用默认值,例如: 0.然后,在您的控制器中,如果“day”具有默认值(day == 0),则显示整个月等。

$route1 = new Zend_Controller_Router_Route(
    ':year/:month/:day',
    array(
        'controller' => 'news',
        'action'     => 'year',
        'year' => '0',
        'month' => '0',
        'day' => '0'
    )
);