<?php<liu21st@gmail.com>namespace Think\Controller;
use Think\Controller;
class RestController extends Controller {
protected $_method = '';
protected $_type = '';
protected $allowMethod = array('get','post','put','delete');
protected $defaultMethod = 'get';
protected $allowType = array('html','xml','json','rss');
protected $defaultType = 'html';
protected $allowOutputType= array(
'xml' => 'application/xml',
'json' => 'application/json',
'html' => 'text/html',
);
public function __construct() {
if(''==__EXT__) { $this->_type = $this->getAcceptType();
}elseif(!in_array(__EXT__,$this->allowType)) {
$this->_type = $this->defaultType;
}else{
$this->_type = $this->getAcceptType() == __EXT__ ? __EXT__ : $this->defaultType;
}
$method = strtolower(REQUEST_METHOD);
if(!in_array($method,$this->allowMethod)) {
$method = $this->defaultMethod;
}
$this->_method = $method;
parent::__construct();
}
public function __call($method,$args) {
if( 0 === strcasecmp($method,ACTION_NAME.C('ACTION_SUFFIX'))) {
if(method_exists($this,$method.'_'.$this->_method.'_'.$this->_type)) { $fun = $method.'_'.$this->_method.'_'.$this->_type;
$this->$fun();
}elseif($this->_method == $this->defaultMethod && method_exists($this,$method.'_'.$this->_type) ){
$fun = $method.'_'.$this->_type;
$this->$fun();
}elseif($this->_type == $this->defaultType && method_exists($this,$method.'_'.$this->_method) ){
$fun = $method.'_'.$this->_method;
$this->$fun();
}elseif(method_exists($this,'_empty')) {
$this->_empty($method,$args);
}elseif(file_exists_case($this->view->parseTemplate())){
$this->display();
}else{
E(L('_ERROR_ACTION_').':'.ACTION_NAME);
}
}
}
protected function getAcceptType(){
$type = array(
'html' => 'text/html,application/xhtml+xml,*
protected function encodeData($data,$type='') {
if(empty($data)) return '';
if('json' == $type) {
$data = json_encode($data);
}elseif('xml' == $type){
$data = xml_encode($data);
}elseif('php'==$type){
$data = serialize($data);
$this->setContentType($type);
return $data;
}
public function setContentType($type, $charset=''){
if(headers_sent()) return;
if(empty($charset)) $charset = C('DEFAULT_CHARSET');
$type = strtolower($type);
if(isset($this->allowOutputType[$type])) header('Content-Type: '.$this->allowOutputType[$type].'; charset='.$charset);
}
protected function response($data,$type='',$code=200) {
$this->sendHttpStatus($code);
exit($this->encodeData($data,strtolower($type)));
}
}