不知道大家知不知道zend framework有一个action helper context switch来帮助解决暴露不同的数据格式
此代码片段收集自http://www.zfsnippets.com/snippets/view/id/48
## /application/controllers/EnglandController.php
<?php
/**
* Simple example of using the context switch
*
* @author Dave Marshall
*/
class EnglandController extends Zend_Controller_Action
{
public function init()
{
$this->_helper->contextSwitch()
->addActionContext('a', array('xml', 'json'))
->setAutoJsonSerialization(true)
->initContext();
}
public function aAction()
{
$this->view->team = 'a';
$this->view->players = array(
'David James',
'Ashley Cole',
'John Terry',
'Rio Ferdinand',
'Glen Johnson',
'Joe Cole',
'Steven Gerrard',
'Frank Lampard',
'David Beckham',
'Wayne Rooney',
'Michael Owen',
);
}
}
## /application/views/scripts/england/a.xml.phtml
<?php echo "<?xml version="1.0" ?>";?>
<team>
<name><?php echo $this->team; ?></name>
<players>
<?php foreach($this->players as $player):?>
<player><?php echo $player; ?></player>
<?php endforeach; ?>
</players>
</team>
## http://yourhost/england/a/format/xml would output
<?xml version="1.0" ?><team>
<name>a</name>
<players>
<player>David James</player>
<player>Ashley Cole</player>
<player>John Terry</player>
<player>Rio Ferdinand</player>
<player>Glen Johnson</player>
<player>Joe Cole</player>
<player>Steven Gerrard</player>
<player>Frank Lampard</player>
<player>David Beckham</player>
<player>Wayne Rooney</player>
<player>Michael Owen</player>
</players>
</team>
## http://yourhost/england/a/format/json would output
{
"team":"a",
"players":[
"David James",
"Ashley Cole",
"John Terry",
"Rio Ferdinand",
"Glen Johnson",
"Joe Cole",
"Steven Gerrard",
"Frank Lampard",
"David Beckham",
"Wayne Rooney",
"Michael Owen"
]
}