Mental Ramblings Gets Fed
In a recent post I had described the way to implement an xml sitemap generator for search engines, using the CakePHP XML Help with RequestHandler Component. I have tweaked that slightly to implement rss feeds for the posts.
First the controller action. Here we see the channel settings 'title' and 'description' which are used in the default rss layout used in /cake/libs/views/layouts/rss/default.ctp
{
Configure::write ('debug', 0);
$this->Post->recursive = 0;
$this->set('channel', array('title' => 'Latest Thoughts From Mental Ramblings', 'description' => 'CakePHP Related Blog Posts From A Programmer's Mind'));
$this->set( 'posts', $this->paginate() );
$this->viewPath .= '/rss';
$this->layoutPath = 'rss';
}
Next up is /app/views/posts/rss/feed.ctp
$rss->addNs("atom", "http://www.w3.org/2005/Atom");
$rss->addNs("rc");
$rss->addNs("wf");
$rss->addNs("dc");
echo '<atom:link href="http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'] . '" rel="self" type="application/rss+xml" />' . "\n\r";
echo $rss->items($posts, 'transformRSS');;
function transformRSS($data) {
return array(
'title' => $data['Post']['title'],
'link' => array('controller' => 'Posts', 'action' => 'view', $data['Post']['name']),
'guid' => array('controller' => 'Posts', 'action' => 'view', $data['Post']['name']),
'description' => $data['Post']['excerpt'],
'author' => $data['User']['username'],
'pubDate' => $data['Post']['created']
);
}
?>
The $rss->XXX () functions are all standard RssHelperfunctions in CakePHP 1.2 and can be found in the api. I use acallback function in $rss->items() to transform the $posts data from the controller into data to be used in the RssHelper.
The final thing to adjust is in the /app/config/routes.php file I have added in a simple route from /posts.rss to /posts/feed.


nate Said:
You're writing a lot of extra controller code there that you don't have to. The proper way to do it is detailed here: http://cake.insertdesignhere.com/posts/view/8