在某些時候,需要Action來輸出例如xml等格式
這時候就可以透過contextSwitch()來選擇你要輸出的格式
首先在Controller中加入init()函式,選擇你想要的輸出格式
indexController
<?php
class IndexController extends Zend_Controller_Action {
public function init(){
$this->_helper->contextSwitch()
//加入Context:json、xml(加在indexAction裡)
->addActionContext('index', 'json')
->addActionContext('index', 'xml')
->initContext();
}
public function indexAction() {
$this->view->test = 'TEST';
}
}
?>
其中json可以直接輸出,不需要再令外的view來顯示
只要用http://url/Zend/?format=json
就可以看到
{"test":"TEST"}
除了json之外,其他格式例如成xml,必須再做一個樣板
樣板名稱就是以Action名稱.格式.phtml
以範例indexAction來說,需要在views/scripts/index/(也就是放index.phtml的目錄)裡再新增一個index.xml.phtml
index.xml.phtml
<?xml version="1.0" encoding="UTF-8"?> <root> <test><?php echo $this->test; ?></test> </root>
輸入http://url/Zend/?format=xml就可以看到結果
除了這兩樣格式之外,如果要新增其他格式,例如RSS格式,就必須自訂Context
indexController
<?php
class IndexController extends Zend_Controller_Action {
public function init(){
$this->_helper->contextSwitch()
//自訂Context
->addContext('rss', array('suffix' => 'rss'))
->addActionContext('index', 'rss')
->initContext();
}
public function indexAction() {
$this->view->test = 'TEST';
}
}
?>
同樣要另外寫一個樣板
index.rss.phtml
<?xml version="1.0" encoding="UTF-8"?> <rss version="2.0"> <channel> <title><?php echo $this->test; ?></title> </channel> </rss>
除了上述那些格式,如果有使用到Ajax時,因為contextSwitch裡是沒有註冊HTML context的,必須使用AjaxContext
<?php
class IndexController extends Zend_Controller_Action {
public function init(){
$this->_helper->ajaxContext()
->addActionContext('index', 'html')
->initContext();
}
public function indexAction() {
$this -> view -> test = array("name"=>"Johnson");
}
}
?>
AjaxContext的context-suffix是ajax,所以必須再建立index.ajax.phtml
<div><?php print_r($this -> test); ?></div>
輸入http://url/Zend/?format=html就可以看到結果