Cakephp博客教程-控制器$id

Cakephp博客教程-控制器$id,cakephp,cakephp-2.0,cakephp-2.3,Cakephp,Cakephp 2.0,Cakephp 2.3,在PostsController部分的CakePHP2.0博客教程中,我需要一些帮助 我无法理解参数中的$id来自何处,它被定义为$id=null,因此我的理解是$id应该为null,但它不是null public function view($id = null) { if (!$id) { throw new NotFoundException(__('Invalid post')); } $post = $this->Post->fi

在PostsController部分的CakePHP2.0博客教程中,我需要一些帮助

我无法理解参数中的
$id
来自何处,它被定义为
$id=null
,因此我的理解是
$id
应该为null,但它不是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
的实际值来自url,在本例中,
cakephp/posts/view/$id
但我想知道url中的
$id
是如何通过
PostsController
调度程序从url中获取参数,并将其作为参数传递给控制器操作的,以便您可以使用它们执行操作,例如,通过URL中指定的ID查找博客文章

如果您请求类似的URL,则默认值为
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);
    }
}

只是想补充一点,最好在
$post=$this->post->findByid($id)之后执行if语句
,并检查
是否(空($post))
,或将
更改为空($id)
$此->发布->存在($id)
。您可以拥有一个无效post的非空ID,实际上需要一个
NotFoundException
。我通常在自己的CakePHP应用程序中使用
if(!$this->ModelName->exists($id))
方法。以上只是一个简单的例子。