Cakephp博客教程 - Controller $ id

时间:2013-12-11 12:42:41

标签: cakephp cakephp-2.0 cakephp-2.3

我需要在PostsController部分的cakephp 2.0的博客教程中提供一些帮助

http://book.cakephp.org/2.0/en/tutorials-and-examples/blog/part-two.html

我无法理解$id来自参数的定义为$id = null所以我的理解为$id应为null但不是空

public function view($id = null) {
    if (!$id) {
        throw new NotFoundException(__('Invalid post'));
    }

    $post = $this->Post->findById($id);
    if (!$post) {
        throw new NotFoundException(__('Invalid post'));
    }
    $this->set('post', $post);
}

我知道$id的真正价值来自网址,在本例中为cakephp/posts/view/$id,但我想知道网址中的$id如何通过PostsController }

1 个答案:

答案 0 :(得分:2)

调度程序从URL获取参数并将它们作为参数传递给控制器​​操作,以便您可以使用它们执行操作,即通过URL中指定的ID查找博客文章。

如果您请求 http://example.com/posts/view/ 等网址,则默认值为null。您没有指定ID,因此这将是null值,您可以在控制器操作中抛出404错误:

<?php
class PostsController extends AppController {

    public function view($id = null) {
        if (is_null($id)) {
            throw new NotFoundException();
        }

        $post = $this->Post->findById($id);

        $this->set('post', $post);
    }
}