[译]用cakephp来构建一个blog系统

文章分类:misc  查看次数:523 + 107

原文地址:http://manual..org/appendix/blog_tutorial

原文太长,这里就挑主要的翻译一下

第一部分:简要介绍

所需的软件配置
一个web服务器,比如说apache
一个数据库系统,比如mysql
基本的php方面知识
基本的MVC设计模式

第二部分:获取

最新的下载地址:http://cakeforge.org/projects//
下载完之后,目录文件应该像以下这样

    define ('BASE_URL', env('SCRIPT_NAME'));
   

这样URL就像是www.example.com/index.php/controllername/actionname/param而不是www.example.com/controllername/actionname/param

第六部分:创建一个post模块

model是的面包和牛奶,创建一个model将会与数据库建立起交互,比如增加,编辑,删除等等。
/app/models/post.php

    <?php

class Post extends AppModel
{
    var $name = 'Post';
}

?>
   

或许会有疑问,为什么是Post,而不是Posts,因为cake已经设置好了以复数的形式连接,比如数据库的表名为users,则model $name就应该为User

第七部分:创建一个post的控制器

控制器(controller)是用于post的交互的,也包含所有post的行为(actions)
/app/controllers/posts_controller.php

    <?php

class PostsController extends AppController
{
    var $name = 'Posts';
}

?>
   

下面我们来加入一些函数
/app/controllers/posts_controller.php (index action added)

<?php

class PostsController extends AppController
{
    var $name = 'Posts';

    function index()
    {
        $this->set('posts', $this->Post->findAll());
    }
}

?>
 

定义了index()函数,那么在用户访问www.example.com/posts/index的时候触发,同理,如果定义了一个foobar函数,那么可以访问www.example.com/posts/foobar
函数的主体只有一句,就是返回所有posts表里的内容,并将其赋予$posts。

第八部分:创建一个post的模版

前面已经定义了模块和控制器,这次来创建一个视图模版。
视图模版可以混合html和php。
别忘了,我们已经在index()函数定义了一个$posts,先让我们来看看它都有什么。

// print_r($posts) output:
    Array
(
    [0] => Array
        (
            [Post] => Array
                (
                    [id] => 1
                    [title] => The title
                    [body] => This is the post body.
                    [created] => 2006-03-08 14:42:22
                    [modified] =>
                )
         )
    [1] => Array
        (
            [Post] => Array
                (
                    [id] => 2
                    [title] => A title once again
                    [body] => And the post body follows.
                    [created] => 2006-03-08 14:42:23
                    [modified] =>
                )
        )
    [2] => Array
        (
            [Post] => Array
                (
                    [id] => 3
                    [title] => Title strikes back
                    [body] => This is really exciting! Not.
                    [created] => 2006-03-08 14:42:24
                    [modified] =>
                )
         )
)
   

cake的视图文件存储于/app/views,views下面的文件夹对应一个控制器,在这里就是posts。
/app/views/posts/index.thtml

<h1> 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>
 

你可能注意到了,代码里面出现了$html,这是HtmlHelper的一个实例。link()方法会生成一个链接。如果点击这个链接,将会打开类似/posts/view/some_id的URL
这里我们添加一个view方法
/app/controllers/posts_controller.php (view action added)

<?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());
    }
}
?>
 

这样如果用户提交/posts/view/3,那么3将作为参数传递给view函数。
创建一个view模版
/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>
 

第九部分:添加文章

为PostsController添加add方法
/app/controllers/posts_controller.php (add action added)

<?php

class PostsController extends AppController
{
    var $name = 'Posts';

    function index()
    {
         $this->set('posts', $this->Post->findAll());
    }

    function view($id)
    {
        $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');
            }
        }
    }
}

?>
 

我们来看看add方法。如果数据不是空的话,保存数据。如果保存失败,则给出失败的原因返回到客户端。(save方法会检测数据类型)
flush方法,输出一个带链接的语句。

第十部分:数据检测

表单的数据检测是一项比较枯燥的事,cake使它变得简单而有效。
要充分发挥验证的功能,需要在视图中使用HtmlHelper

/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>
 

tagErrorMsg()函数将会在数据验证失败时出现。
但是cake如何知道我们的数据类型呢,这就需要在创建model的时候指定

/app/models/post.php (validation array added)

<?php

class Post extends AppModel
{
    var $name = 'Post';

    var $validate = array(

        'title'  => VALID_NOT_EMPTY,
        'body'   => VALID_NOT_EMPTY

    );
}

?>
 

$validation告诉cake各字段的数据类型。

第十一部分:删除文章

/app/controllers/posts_controller.php (delete action only)

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

/app/views/posts/index.thtml (add and delete links added)

<h1> 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>
 

第十二部分:编辑文章

也很简单,就像这样

/app/controllers/posts_controller.php (edit action only)

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');
        }
    }
}
 

/app/views/posts/edit.thtml

<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>
 

/app/views/posts/index.thtml (edit links added)

<h1> 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>
 

第十三部分:流程(routes)

这部分是可选的,但对于理解URL的走向很有帮助。
cake默认的规则是使用户访问网站的根目录(http://www.example.com),但是我们要转到PagesController,并执行view,所以我们要改变默认的规则,默认的流程

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

修改后的流程

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

评论

发表评论