/**//* First, create our posts table: */ CREATETABLE posts ( id INT UNSIGNED AUTO_INCREMENT PRIMARYKEY, title VARCHAR(50), body TEXT, created DATETIMEDEFAULTNULL, modified DATETIMEDEFAULTNULL ); /**//* Then insert some posts for testing: */ INSERTINTO posts (title,body,created) VALUES ('The title', 'This is the post body.', NOW()); INSERTINTO posts (title,body,created) VALUES ('A title once again', 'And the post body follows.', NOW()); INSERTINTO posts (title,body,created) VALUES ('Title strikes back', 'This is really exciting! Not.', NOW());
<?php require_once ('cake/app_model.php'); class Post extends AppModel { public$name='Post'; public$validate=array( 'title'=> VALID_NOT_EMPTY, 'body'=> VALID_NOT_EMPTY ); } ?>
增加Cotroller模块:
app/controllers/posts_controller.php
代码:
<?php require_once ('cake/app_controller.php'); class PostsController extends AppController { public$name='Posts'; function index() { $this->set('posts',$this->Post->findAll()); } function view($id=null) { $this->Post->id =$id; $this->set('post',$this->Post->read()); } function add() { if (!empty($this->data)) { if ($this->Post->save($this->data)) { //$this->flash('Your post has been saved.','/posts'); $this->redirect("/posts/index"); } } } function delete($id) { $this->Post->del($id); //$this->flash('The post with id: '.$id.' has been deleted.', '/posts'); $this->redirect("/posts/index"); } 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'); $this->redirect("/posts/index"); } } } } ?>
增加页面模块:
/app/views/下追加posts文件夹,然后再添加4个页面(一般后缀为.rhtml)
代码依次为:
index.thtml
<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>