Table of Contents

Icing on the Blog

This tutorial shows you how to use more advanced Cake methods to improve on the Baking a Blog with Cake example.

Adding Table Prefixes to a Model

Alright, so if your interested in using table prefixes, such as blog_, in front of your tables this section is for you, if not, skip to the next one.

Warning: This method is probably going to change in a future release.

First make sure you have a table called blog_posts. You can use the posts table from the Beginning Blog tutorial and just rename it to blog_posts.

Now add the following to your model, post.php, which can be found in /app/models. (Update: Now you don’t have to specify it in functions, just declare the variable and that’s it.)

var $tablePrefix = 'blog_';

Ta da! That’s it, you don’t have to do anything else. Every call to the database in that model will append blog_ to the front of the table, but all references to the model in the views is still simply post or posts.

Adding Good Looking Dates

To get more readability in the dates, we include another helper in the controller:

<?php
 
class PostsController extends AppController 
{
	var $name = 'Posts';
	var $helpers = array( 'Html', 'Javascript', 'Time' );
   # the rest omitted for brevity's sake

Now, we include more Helpers available in the Views of this controller. They’re now accessible with names like $html, $javascript, or $time.

To use the TimeHelper, let’s add a call to the newly included Helper. In our index view, we add a small call on the “created” line:

<h1>Blog posts</h1>
<table>
    <tr>
        <th>Id</th>
        <th>Title</th>
        <th>Created</th>
    </tr>
    <?php foreach ($posts as $post): ?>
    <tr>
        <td><?php echo $post['Post']['id']; ?></td>
        <td>
            <?php echo $html->link( $post['Post']['title'], "/posts/view/{$post['Post']['id']}" ); ?>
            <?php echo $html->link('Delete', "/posts/delete/{$post['Post']['id']}", null, "Are you sure you want to delete post entitled '{$post['Post']['title']}'?")?>
            <?php echo $html->link('Edit', "/posts/edit/{$post['Post']['id']}"); ?>
 
        </td>
        <td><?php echo $time->timeAgoInWords($post['Post']['created']) ; ?></td>
    </tr>
    <?php endforeach; ?>
</table>
 
<?php echo $html->link('Add new post', '/posts/add') ?>

The only change here is the $time→timeAgoInWords() call on the created field.

Adding a Recent Post Element to Another Page

To have your recent posts appear on a different page, it’s necessary to create a component, which manages the data, and an element which displays the data.

  • Create /app/controllers/components/recent_posts.php with the following contents
<?php
class RecentPostsComponent extends Object
{
   var $controller = true;
 
    function startup (&$controller) {
        $this->controller = &$controller;
        $Post = new Post;
        $data = $Post->findAll(
                null,
                null,
                'Post.modified DESC',
                $number
            );
        $this->controller->set('RecentPosts',$data);
    }
}
?>
  • Call the component in any controller you want to display your recent posts
    class MyOtherController extends AppController
    {
        // Nothing else required
        var $components = array('RecentPosts');
    }

Or add var $components = array(’RecentPosts’); to the top of the PostsController

  • Create /app/views/elements/recent_posts.thtml with the following contents
<div id="recentposts">
    <h2>Latest Posts!</h2>
    <?php
    foreach ($RecentPosts as $Post): ?>
        <div class="itemtitle">
            <?php echo $html->link($Post['Post']['title'], "/posts/view/{$Post['Post']['id']}")?>
        </div>
        <div class="itembody">
            <?php echo $Post['Post']['body']?>
        </div>
        <div class="itemdate">
            <?php echo $time->timeAgoInWords($Post['Post']['created'])?>
        </div>
    <?php endforeach;?>
    <?php echo $html->link('Archive', "/posts/")?>
</div>
  • In any view you want to see your recent posts render the element.
...
<?php echo $this->renderElement('recent_posts',$params) ?>
...

And that’s it, if you go to /MyOtherController/ now, you’ll have your recent posts included on the page - add a dash of css formatting and you’re ready to go. If you placed the Component items in the PostsController in an action such as view, then add the above renderElement code in the corresponding action thtml file (i.e. view.thtml).

Adding an RSS feed using FeedCreator

(This section has been inspired by Olle’s rudimentary explanation in earlier material.) Please be aware that there will be built-in RSS support in the coming beta release.

But let’s start.

The first thing we need is a special layout for our RSS feed. We create in /app/views/layouts the file rss.thtml.

<?php 
echo $content_for_layout;
?>


To our PostsController we add an action rss which is rather simple.

function rss()
{
    $this->layout = 'rss';
    $this->set('data', $data = $this->Post->findAll(
            null,
            null,
            'modified DESC', // Sort order
            5 // Number to be returned
            ));
}


The last step we have to do is to create the view rss.thtml in app/views/posts. We will use the LGPL-licensed FeedCreator class to create the RSS feed. Get the FeedCreator TAR-ball. Extract the feedcreator.class.php file and put it in your vendors directory.

<?php
    vendor("feedcreator.class"); 
	
    $rss = new UniversalFeedCreator(); 
    $rss->title = "my title"; 
    $rss->description = "my description"; 
    $rss->link = "my link"; 
    $rss->syndicationURL = "my syndication url";
    // Initialize the cssStyleSheet var, needed to avoid an error with FeedCreator version 1.7.2-mod (latest version at time of writing)
    $rss->cssStyleSheet = "";
 
	
    foreach ($data as $post)
    {
        $item = new FeedItem(); 
        $item->title = $post['Post']['title']; 
    	$item->link = "link"; 
    	$item->description = $post['Post']['body'];
        $newdate = $post['Post']['created'];
        list($date,$hours) = split(' ', $newdate);
        list($year,$month,$day) = split('-', $date);
        list($hour,$min,$sec) = split(':', $hours);
        $date = date("r", mktime($hour, $min, $sec, $month, $day, $year));
    	$item->date = $date; 
    	$item->source = "source"; 
    	$item->author = "author"; 
     
    	$rss->addItem($item);
    }
	
    $rss->outputFeed();
?>


Now, just edit those customizable strings in there, and you’re on the RSS superhighway.

Now what?

So, you’ve seen some Cake in action - you’ve got an application, you’ve already tweaked it.

But you’re hungry for more, and want to read a complete application, from top to bottom. Well, then here is a suggestion: read some of the projects at http://www.cakeforge.org - there is a blogging system (rdBloggery) in rdOS and a growing e-commerce system in BakeSale.

 
tutorials/blog_tutorial_-_2.txt · Last modified: 2006/06/01 13:07 by drayen