Building an interactive website using CakePHP - Part 1

view a random?

Step 0:

For starters, I am following the example - building a blog using CakePHP in the CakePHP Manual. From there I’ll make it do what I want, but I’ll also want to add other functionality. That will likely take a while, so you’ll have to wait. Part 1 covers the development done on day one.

Don’t forget to check out the Cake naming conventions - they’ll make your baking easier.

Step 1:

I’ve got the right environment - MySQL, Apache httpd, and PHP installed.

Step 2:

I’ve got Cake.

Step 3:

Create the database. Create a user who only has permission for that database, I also restrict their permissions to select, update, insert, delete. You might even want to remove delete; why give the opportunity to drop your user table?

/* First, create our posts table: */
CREATE TABLE posts (id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,title VARCHAR(50),body TEXT,
created DATETIME DEFAULT NULL,
modified DATETIME DEFAULT NULL
);/* Then insert some posts for testing: */
INSERT INTO posts (title,body,created)
VALUES ('The title', 'This is the post body.', NOW());
INSERT INTO posts (title,body,created)
VALUES ('A title once again', 'And the post body follows.', NOW());
INSERT INTO posts (title,body,created)
VALUES ('Title strikes back', 'This is really exciting! Not.', NOW());

Step 4:

Setup Cake database configuration.

A copy of Cake’s database configuration file is found in /app/config/database.php.default. Make a copy of this file in the same directory, but name it database.php. The config file should be pretty straightforward: just replace the values in the $default array with those that apply to your setup, like the following:


var $default = array('driver' => 'mysql',
'connect' => 'mysql_pconnect',
'host' => 'localhost',
'login' => 'cakeBlog',
'password' => 'c4k3-rUl3Z',
'database' => 'cake_blog_tutorial' );

Step 5:

Make sure mod_rewrite is on - it’s a give away if no images/css show. mod_rewrite is a great way of improving your URL readability.

Step 6:

Create a post model /app/models/post.php

<?php
class Post extends AppModel{var $name = 'Post';}
?>

More info on Cake Models…

Step 7:

Create a post controller /app/controllers/posts_controller.php


<?php
class PostsController extends AppController
{
var $name = 'Posts';
function index()
{
$this->set('posts', $this->Post->findAll());
}

function view($id = null)
{
$this->Post->id = $id;
$this->set(’post’, $this->Post->read());
}
}
?>

By defining function index() in our PostsController, users can now access the logic there by requesting www.example.com/posts/index. Similarly, if we were to define a function called foobar(), users would be able to access that at www.example.com/posts/foobar.

I’ll have to read up on the controller to work out how it knows about Post! And there is a lot to grasp in there… might just stick with the simple example for a while.

More info on Cake Controllers…

Step 8:

Creating Post Views, create a posts folder in the/app/views folder and create the file: /app/views/posts/index.thtml. To format this post data in a nice table, our view code might look something like this:

<h1>Blog posts</h1><table><tr><th>Id</th>
<th>Title</th>
<th>Created</th>
</tr>
<!-- Here's where we loop through our $posts array, printing out post info -->
<?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']); ?>
</td>
<td><?php echo $post['Post']['created']; ?></td>
</tr>
<?php endforeach; ?>
</table>

The object $html is an instance of the HtmlHelper class - Helpers allow the integration of JavaScript and AJAX. More about Helpers…More about views…

At this point you should be able to point your web browser to example.com/posts/index and see an index of the blog posts.

cake blog index

Now let’s create the view for our new ‘view’ action and place it in /app/views/posts/view.thtml.

<h1><?php echo $post['Post']['title']?></h1><p><small>Created: <?php echo $post['Post']['created']?></small></p>
<p><?php echo $post['Post']['body']?></p>

Verify that this is working by trying the links at /posts/index or manually requesting a post by accessing /posts/view/1.

Step 9:

Adding posts - not much of a blog without new posts… Add an add function to posts_controller.php:


function add() {
if (!empty($this->data))
{
if ($this->Post->save($this->data))
{
$this->flash('Your post has been saved.','/posts');
}
}
}

Step 10:

Data validation - Add a new thtml view /app/views/posts/add.thtml

<h1>Add Post</h1><form method="post" action="<?php echo $html->url('/posts/add')?>">
<p>

Title:
<?php echo $html->input(’Post/title’, array(’size’ => ‘40′))?>
<?php echo $html->tagErrorMsg(’Post/title’, ‘Title is required.’) ?>
</p>
<p>

Body:
<?php echo $html->textarea(’Post/body’, array(’rows’=>’10′)) ?>
<?php echo $html->tagErrorMsg(’Post/body’, ‘Body is required.’) ?>
</p>
<p>
<?php echo $html->submit(’Save’) ?>
</p>
</form>

Cake integrates form validation into the model: update /app/models/post.php to include the validation array:

<?php
class Post extends AppModel
{
var $name = 'Post';
var $validate = array(
'title' => VALID_NOT_EMPTY,
'body' => VALID_NOT_EMPTY
);
}
?>

Cake has a set of constants for regex validation matches, check them out in he values for those keys are just constants set by Cake that translate to regex matches, check them out in /cake/libs/validators.php

Step 11:

At this stage, who really cares - we know have the ability to write posts, view posts and list posts… they even have validation! But we have the power to do more… So let’s try and delete them.

Add a delete action in /app/controllers/posts_controller.php


function delete($id)
{
$this->Post->del($id);
$this->flash('The post with id: '.$id.' has been deleted.', '/posts');
}

Update the index view to allow users to delete posts /app/views/posts/index.thtml

<h1>Blog posts</h1>
<p><?php echo $html->link('Add Post', '/posts/add'); ?></p>
<table>
<tr>
<th>Id</th>
<th>Title</th>
<th>Created</th>
</tr>
<!-- Here's where we loop through our $posts array, printing out post info -->
<?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?'
)?>
</td>
</td>
<td><?php echo $post['Post']['created']; ?></td>
</tr>
<?php endforeach; ?>
</table>

Step 12:

A basic blog in less than 2 hours.. plus a summarised version of the tutorial - it’s is pretty easy to put together. And just a couple more steps to go… editing the posts. Add an edit action to the controller:


function edit($id = null)
{
if (empty($this->data))
{
$this->Post->id = $id;
$this->data = $this->Post->read();
}
else
{
if ($this->Post->save($this->data['Post']))
{
$this->flash('Your post has been updated.','/posts');
}
}
}

Create a edit.thtml view:

<h1>Edit Post</h1>
<form method="post" action="<?php echo $html->url('/posts/edit')?>">
<?php echo $html->hidden('Post/id'); ?>
<p>

Title:
<?php echo $html->input(’Post/title’, array(’size’ => ‘40′))?>
<?php echo $html->tagErrorMsg(’Post/title’, ‘Title is required.’) ?>
</p>
<p>

Body:
<?php echo $html->textarea(’Post/body’, array(’rows’=>’10′)) ?>
<?php echo $html->tagErrorMsg(’Post/body’, ‘Body is required.’) ?>
</p>
<p>
<?php echo $html->submit(’Save’) ?>
</p>
</form>

Update our index to allow editing posts:

<h1>Blog posts</h1>
<p><?php echo $html->link("Add Post", "/posts/add"); ?>
<table>
<tr>
<th>Id</th>
<th>Title</th>
<th>Created</th>
</tr>
<!-- Here's where we loop through our $posts array, printing out post info -->
<?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?'
)?>
<?php echo $html->link('Edit', '/posts/edit/'.$post['Post']['id']);?>
</td>
</td>
<td><?php echo $post['Post']['created']; ?></td>
</tr>
<?php endforeach; ?>
</table>

Step 13:

The end… almost. If you want the code you have written to appear when a user browses your website, then you’ll need to edit the Cake configuration. So the route the user travels is the one you desire…

Cake’s routing is found in /app/config/routes.php. You’ll want to comment out or remove the line that looks like this:

$Route->connect ('/', array('controller'=>'pages', 'action'=>'display', 'home'));

This line connects the URL / with the default Cake home page. We want it to connect with our own controller, so add a line that looks like this:

$Route->connect ('/', array('controller'=>'posts', 'action'=>'index'));

This should connect users requesting ‘/’ to the index() action of our PostsController.

Read more about route configuration in section 3 of the config chapter.

Conclusion:

Wicked, put that together in less than 2 hours.. which included having breakfast. I’ve uploaded the cake blog to http://cake.nzfusion.com ~ so you can check it out there.

Though what has completely stumped me, is working on my desktop environment, everything worked fine. Then uploading it to the web - everything has gone poos. I have changed the database credentials, and URL… ah well, time to go to the gym and have lunch.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Facebook
  • Google
  • MisterWong
  • Reddit
  • Scoopit
  • StumbleUpon
  • Technorati
  • rss

3 Comments

  1. ravindra
    Posted April 16, 2008 at 10:59 pm | Permalink

    i can not understand all this very well, this is very hadrd launguage ithink.

  2. Posted July 15, 2008 at 10:21 pm | Permalink

    Wow, it really is a pain displaying source code in Wordpress…

    I’ve not been able to find anything that really suits my needs. Any suggestions?

  3. Santu Saha
    Posted October 23, 2008 at 8:20 pm | Permalink

    Thanks
    it is really good script for start CakePHP.
    Thanks again.

2 Trackbacks

  1. […] Building an interactive website using CakePHP - Part 1 […]

  2. […] very happy to say, the fix worked. But you’ll need to do a few amendments to the cakePHP blog tutorial for it to work in the Beta release. But the great part about the Beta release, is it tells […]

Post a Comment

You must be logged in to post a comment.