CakePHP DataSources
TweetWhen specifying a database connection configuration in app/config/database.php, CakePHP transparently uses the corresponding database datasource for all model operations. So, even though you might not have known about datasources, you’ve been using them all along.
Most people, however, are interested in writing datasources for external sources of data, such as remote REST APIs or even an LDAP server.
The usage of such DataSources in CakePHP is quite trivial. I will show how easy it is on an excellent example by LoadSys which created RSS DataSource. You can download it here.
After you download the DataSource, unpack it to your /app/models/datasources directory of your CakePHP installation. To use the custom DataSource, we need to create a configuration for it inside our /app/config/database.php:
var $codeforestNews = array(
'datasource' => 'rss',
'feedUrl' => 'http://feeds.feedburner.com/codeforest',
'encoding' => 'UTF-8',
'cacheTime' => '+1 day',
);
Now, we need to create our model for the DataSource. Create /app/models/codeforest_news.php and enter:
class CodeforestNews extends AppModel {
var $useTable = false;
var $useDbConfig = 'codeforestNews';
}
Basically, we are telling our model that we are not using tables and which database configuration to use.
Now, we can use this model inside our Controller:
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') );
}
}
As you can see, this DataSource is even allowing us to paginate the result.
An example view for showing the results on a page would look similar to this:
<?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>
You can see it in action:
Of course, everything is neatly cached, so the overhead of fetching the news through RSS is reduced.
This is a great example of using custom DataSource in CakePHP. There are many datasources available on the net, but the best resource is available on GitHub.
You can use them in a similar way like shown in a LoadSys example above.
Another great example of custom DataSources in CakePHP is Neil Crookes’ one that is dealing with all kind of REST API calls.



Hi,
That’s a really great tutorial.
Could you tell me a way to use a local xml file as the datasourcs?