cakephp中的数据源其实是个好东西,假如你有多种形式的数据源,比如REST,RSS, 

JSON等,你可以编写cakephp的插件,去读取这些数据源.本文以编写一个读取RSS格式数据源

的做例子,讲解其使用.


代码在http://www.loadsys.com/files/rss_source.zip中可以下载,

把解压的代码放在/app/models/datasources 下,并设置

app/config/database.php如下


var $codeforestNews = array(


'datasource' => 'rss',


'feedUrl' => 'http://feeds.feedburner.com/codeforest',


'encoding' => 'UTF-8',


'cacheTime' => '+1 day',


);

接着,创建

/app/models/codeforest_news.php

class CodeforestNews extends AppModel {


var $useTable = false;


var $useDbConfig = 'codeforestNews';


}

这里说明了,不使用数据库中的表,而直接使用datasource作为数据源

再看控制层:

class NewsController extends AppController {


var $name = 'News';


var $uses = array('CodeforestNews');





function index() {


$this->paginate = array(


'limit' => 10,


'order' => array(


'CodeforestNews.pubDate' => 'desc',


),


);


$this->set('news', $this->paginate('CodeforestNews') );


}


}

可以看到,甚至是可以排序的.

在页面中:



<?php foreach( $news as $newsItem ) : ?>

<?php echo $html->link($newsItem['CodeforestNews']['title'], $newsItem['CodeforestNews']['link']); ?><br/>

<em><?php echo $newsItem['CodeforestNews']['pubDate']; ?></em>

<hr>

<?php endforeach; ?>

<div class="paging">

<?php echo $paginator->prev('<< '.__('previous', true), array(), null, array('class'=>'disabled'));?>

| <?php echo $paginator->numbers();?>

<?php echo $paginator->next(__('next', true).' >>', array(), null, array('class'=>'disabled'));?>

</div>


DEMO效果为:

​​​ http://www.codeforest.net/demo/cake_data_sources/news/index/page:2
​​​
查看CAKEPHP手册,可以知道,要写datasources,实现如下方法之一即可:

create($model, $fields = array(), $values = array())

read($model, $queryData = array())

update($model, $fields = array(), $values = array())

delete($model, $id = null)