`
lfq618
  • 浏览: 85488 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Zend Framework 中配合 Zend_Config 实现路由

阅读更多

Zend Framework 的路由转发功能不仅可以让 url 变得简洁易记,而且非常对 SEO 非常有益,zf 的路由转发有着多样的配置方法,能实现各种转发需求。

随着站点复杂程度的增加,我们会有越来越多的转发规则,而将这些规则独立到一个文件中,是一个非常好的习惯。本文讲解的是将转发规则存放在单独的配置文件里面,然后配合 Zend_Config 实现转发的方法。

对于直接在程序中实现转发设置,手册上有简单的示例:

PHP:

  • <?php
  • $router = $controller->getRouter(); // 获取路由
  • $route = new Zend_Controller_Router_Route(
  • 'author/:username',
  • array(
  •        'controller' => 'profile',
  •        'action'     => 'userinfo'
  • )
  • );
  • $router->addRoute('user', $route);
  • ?>




上面的规则能将 http://domain.com/author/martel 指向到 http://domain.com/profile/action/author/martel ,这样设置,能大大降低 url 的复杂程度,让 url 简单明了。

我们如果有多条这种规则,就可以考虑将规则放到单独的文件中,手册上是用 ini 文件存储路由规则,我这里则使用 php 数组存储:

PHP:

  • <?php
  • return array(
  • // 将 /view/123 映射为 /default/index/index/id/123
  • 'view' => array(
  •        'route' => 'view/:id',
  •        'defaults' => array(
  •          'module' => 'default',
  •          'controller' => 'index',
  •          'action' => 'index',
  •        ),
  • ),
  • // 将 http://domain.com/author/martel 映射为 http://domain.com/profile/action/author/martel
  • 'profile' => array(
  •        'route' => 'author/:username',
  •        'defaults' => array(
  •          'controller' => 'profile',
  •          'action' => 'userinfo',
  •        ),
  • ),
  • );
  • ?>




对于从数组中取出规则,然后设置 Zend_Controller_Router_Rewrite ,手册也有一段示例:

PHP:

  • <?php
  • $routerConfig = new Zend_Config(require_once 'routes.php');
  • $routerRules = new Zend_Controller_Router_Rewrite();
  • $router->addConfig($routerRules);
  • ?>




不过,手册上没有如何将上面的路由规则应用到当前 controller 的示例,这个也是让新手很头疼的问题,研究过 zend framework 的源码后,我们可以很容易发现解决方法:

PHP:

  • <?php
  • $routerConfig = new Zend_Config('routes.php'); // 加载配置
  • $routerRules = new Zend_Controller_Router_Rewrite();
  • $routerRules->addConfig($routerConfig); // 设置规则
  • $routers = $controller->getRouter(); // 获取路由
  • $routers->addRoutes($routerRules->getRoutes()); // 通过 $routerRules->getRoutes() 获取规则,然后设置
  • ?>
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics