利用Plugin为ZendFramework加上RESTful view

使用ZF1.0的时候发现它的MVC模式的view模板缺省为phtml,而REST接口要求根据客户要求Accept协议头返回不同格式的结果。考察了一下整个Framework,发现可以用Plugin简单地实现不同View模板的选择。下面是Plugin的代码:

<?php

/**
 * Choose correct view for RESTful client
 *  
 * @author lht
 * @version 
 */

final class Restful extends Zend_Controller_Plugin_Abstract {
    public function preDispatch(Zend_Controller_Request_Abstract $request) {
        $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
    	if (preg_match('/text\/xml/i', $request->getHeader('Accept'))) {
            $this->getResponse()->setHeader('Content-Type', 'text/xml; charset=utf-8');
            $viewRenderer->setViewSuffix('pxml');
        } elseif (preg_match('/application\/json/i', $request->getHeader('Accept'))) {
            $this->getResponse()->setHeader('Content-Type', 'application/json; charset=utf-8');
            $viewRenderer->setViewSuffix('pjson');
        } elseif (preg_match('/text\/plain/i', $request->getHeader('Accept'))) {
            $this->getResponse()->setHeader('Content-Type', 'text/plain; charset=utf-8');
            $viewRenderer->setViewSuffix('ptxt');
        }
    }
}
 

 

可以在index.php中这样使用:

$controller = Zend_Controller_Front::getInstance();
$controller->setControllerDirectory('../application/default/controllers');
$controller->throwExceptions(false); // should be turned on in development time 
$controller->registerPlugin(new Restful());
 

 

这样如果Restful client如果Accept: text/xml,那么就会收到.pxml模板的内容。

你可能感兴趣的:(PHP,json,mvc,REST,Zend)