5.4 视图备用格式

也许你会想把最近的博客文章显示为RSS阅读格式。也许你有一份表格数据,你想把它作为CSV格式下载。Solar让这一切变得非常简单,你只需要使用视图备用格式。

首先,你要把备用格式映射到动作方法。

打开文件SYSTEM/source/acme/Acme/App/Blog.php,在_setup()方法中添加$_action_format数组。代码如下:

<?php
protected function _setup()
{
    parent::_setup();
    $this->_model = Solar_Registry::get('model_catalog');
    
    // allow xml as an action format when browsing the index action
    // browsing to index.xml will output to index.xml.php    
    $this->_action_format = array(
        'index' => array('xml')
    );
}   
?>

上面的代码告诉Solar,如果用户访问http://localhost/blog/index.xml,那么:

  1. Solar会查找文件名为index.xml.php的视图,

  2. Solar会设置正确的文档类型(application/xml),

  3. Solar会关闭布局视图功能。

SYSTEM/source/acme/Acme/App/Blog/View目录中创建视图文件index.xml.php

在刚创建的视图文件中加入以下内容:

<items>
<?php foreach ($this->list as $item) : ?>
<item>
    <title><?php echo $this->escape($item->title); ?></title>
</item>
<?php endforeach; ?>
</items>

浏览http://localhost/blog/index.xml,你将看到一个xml格式的页面,它并没有被布局视图包裹。你可能只看到了一堆源代码,这和你的浏览器有关。我们并没有去验证过这些RSS XML的格式。