1.9. 阅读一篇文章

我们已经可以浏览文章列表了,接下来我们来阅读一篇文章。

1.9.1 “Read”方法

找到并打开Blog.php文件。(在此示例中,我们使用vim编辑器,你可以选择自己最喜欢的)

$ vim Blog.php

在类中添加以下代码:

<?php
    public function actionRead($id = null)
    {
        // was an ID specified?
        if (! $id) {
            return $this->_error('ERR_NO_ID_SPECIFIED');
        }
    
        // fetch one blog article by ID
        $this->item = $this->_model->blogs->fetch($id);
    
        // did the blog article exist?
        if (! $this->item) {
            return $this->_error('ERR_NO_SUCH_ITEM');
        }
    }
[Note]Note

在Solar中,URI总是这种形式:/controller/action/param1/param2/.... 。控制器名总是在最前面,接着是方法名,再接着就是方法的参数列表。URI中的参数传递给了方法,所以这样的URI:/blog/read/1对应着PHP方法调用Acme_App_Blog::actionRead(1)。

如果URI中只有/controller,控制器将调用由$_action_default变量定义的默认方法。

1.9.2 “Read”视图文件

为actionRead() 方法创建视图文件read.php。

$ vim Blog/View/read.php

在视图文件read.php中添加如下代码:

<?php $this->head()->setTitle($this->item->title); ?>

<h2><?php echo $this->escape($this->item->title); ?></h2>

<?php echo $this->nl2p($this->item->body); ?>

这个视图获取单条记录并且把它打印到浏览器。