Zend Framework自定义路由一则

经常性的看到如下的url:
http://www.example.com/id/4
或者更干脆
http://www.example.com/3
链接清爽,且搜索引擎友好.
ZF为我们提供了快速简单的实现方式,代码如下
 

//$front为前段控制器实例

$router $front->getRouter();

//实现如http://www.example.com/id/4类型的url

$router->addRoute(

‘test1′

    new Zend_Controller_Router_Route(

     ‘id/:aid’

        array(‘controller’ => ‘index’ ‘action’ => ‘view’)

    ))

    //实现如http://www.example.com/3类型的url

    ->addRoute(

    ‘test2′

    new Zend_Controller_Router_Route(

     ‘/:aid’

        array(‘controller’ => ‘index’ ‘action’ => ‘view’)

        )

);

 

addRoute有两个参数,第一个为URL规则名称,第二个为URL规则的实例,该实例对应类必须实现Zend_Controller_Router_Interface接口,通常为Zend_Controller_Router_Route.
Zend_Controller_Router_Route有三个参数,定义原型为:
public function __construct($route, $defaults = array(), $reqs = array())
其中,
$route为URL匹配的方式, 例如test1实例中的’id/:aid’表示匹配http://www.example.com/id/x,":"代表之后为URL变量分隔符, 表示在实际的URL中aic为变量.
$defaults表示在URL匹配$route指定的形式时默认的各种参数,本例中设置了 控制器为index,动作为view, 所以当URL匹配时则相当于访问了http://www.example.com/index/view/id/x
$reqs则用于指定匹配的正则表达式, 例如 我们可以指定aid为整数时才匹配, 则:
 

$router->addRoute(‘test1′,    

    new Zend_Controller_Router_Route(‘id/:aid’,    

            array(   

                ‘controller’=>‘index’,   

                ‘action’=>‘view’                           

              )   

          ),   

    array(‘aid’=>‘\d+’)   

);

 

简单的介绍下,更多请查看ZF手册.

补充:
定义了’id/:aid’形式的路由规则之后,在动作控制器中,使用
$this->_request->getParam(‘aid’);
来获得id值.

Zend Framework代码实例 — 手工扑捉PHP内部错误

很明显本文的标题不够准确、不能很好体现本文所要表达的意思, 如果你想明白我想说什么, 那么你只好看下去. 呵呵.
今天看ZF源码时看到类Zend_Config_Ini中一段比较有意思的代码:

set_error_handler(array($this‘_loadFileErrorHandler’));           

$iniArray = parse_ini_file($filenametrue); // Warnings and errors are suppressed   

restore_error_handler();   

// Check if there was a error while loading file   

if ($this->_loadFileErrorStr !== null) {   

/**  

@see Zend_Config_Exception  

*/  

    require_once ‘Zend/Config/Exception.php’;   

    throw new Zend_Config_Exception($this->_loadFileErrorStr);   

}   

 

看了这段代码我的第一反应时为什么要这样处理呢?立刻转到错误处理方法看看
 

protected function _loadFileErrorHandler($errno$errstr$errfile$errline)   

{    

    if ($this->_loadFileErrorStr === null) {   

        $this->_loadFileErrorStr = $errstr;   

    } else {   

        $this->_loadFileErrorStr .= (PHP_EOL . $errstr);   

    }   

}

很简单,错误处理方法只是在出错时将类的$_loadFileErrorStr 属性设置为出错字符串.

翻看PHP手册, 从parse_ini_file函数的定义我们可以看出该函数在出现错误时(例如文件不存在,ini文件格式不正确等等)直接输出错误信息, 而不是通过返回值来表达出错信息, 这样我们在使用该函数时就无法很好的控制——在出错时合适的终止程序并给出错误提示或者不可避免的将可能不可理解的错误信息呈现给用户, 为了能够比较简单的手工处理出错信息, 这里采用了这个修改出错处理函数的方法, 由于这个出错函数比较有局限性, 所以之后又立即恢复了出错处理函数.