【问题标题】:Cakephp Blog Tutorial - Controller $idCakephp 博客教程 - 控制器 $id
【发布时间】:2013-12-11 12:42:40
【问题描述】:

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

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

我不明白$id 是从哪里来的,它被定义为$id = null,所以我的理解是$id 应该为空,但它不为空

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 获得的

【问题讨论】:

    标签: cakephp cakephp-2.0 cakephp-2.3


    【解决方案1】:

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

    如果您请求像 http://example.com/posts/view/ 这样的 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-&gt;Post-&gt;findByid($id); 之后执行 if 语句,然后检查 if (empty($post)),或者将 is_null($id) 更改为 !$this-&gt;Post-&gt;exists($id)。您可以拥有一个无效帖子的非空 ID,需要 NotFoundException
    • 确实如此。我通常在我自己的 CakePHP 应用程序中使用if (!$this-&gt;ModelName-&gt;exists($id)) 方法。以上只是作为示例写的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多