Zend Framework 进阶-rewrite(4)

7月 31, 2008 – 10:48 下午

在用zend framework时候定义url重写规则十分方便,也很强大
Zend_Controller_Router_Rewrite是用来处理url重写的基类.
1.怎么用:

  1. <?php
  2. /* Create a router */
  3. $router = $ctrl->getRouter(); // returns a rewrite router by default
  4. $router->addRoute(
  5.     'user',
  6.     new Zend_Controller_Router_Route('user/:username', array('controller' => 'user', 'action' => 'info'))
  7. );

添加一个url重写.意思是当url请求路径符合’user/param’的时候.重定向到user controller的info action上去.而param将作为username的参数.
注意:可以通过$controller->getRequest()->getParam(’username’)取得param的值.不可以通过$_Request取.
2.例子
2.1:重定向到不同的module下面.

  1. <?php
  2. $route = new Zend_Controller_Router_Route(
  3.     ':module/:controller/:action/*',
  4.     array('module' => 'default')
  5. );
  6. $router->addRoute('default', $route);


2.2:主域名 重写

  1. <?php
  2. $route = new Zend_Controller_Router_Route(
  3.     array(
  4.         'host' => 'blog.mysite.com',
  5.         'path' => 'archive'
  6.     ),
  7.     array(
  8.         'module'     => 'blog',
  9.         'controller' => 'archive',
  10.         'action'     => 'index'
  11.     )
  12. );
  13. $router->addRoute('archive', $route);

2.3 Zend_Controller_Router_Route_Static

  1. <?php
  2. $route = new Zend_Controller_Router_Route_Static(
  3.     'login',
  4.     array('controller' => 'auth', 'action' => 'login')
  5. );
  6. $router->addRoute('login', $route);

http://domain.com/login ==>AuthController::loginAction()

2.4 Zend_Controller_Router_Route_Regex

  1. $route = new Zend_Controller_Router_Route_Regex(
  2.     'archive/(\d+)',
  3.     array(
  4.         'controller' => 'archive',
  5.         'action'     => 'show'
  6.     )
  7. );
  8. $router->addRoute('archive', $route);

例子: http://domain.com/archive/2006==>
$values = array(
1 => ‘2006′,
‘controller’ => ‘archive’,
‘action’ => ’show’
);


Post a Comment