首页 > 解决方案 > Symfony 4 使用 URL 检查数据库是否存在页面,否则 404

问题描述

我正在尝试构建一个使用尽可能少的模板的论坛,以便使用数据库来填充论坛真正动态。

我想做的是让我的控制器检查数据库并确保 URL 存在。

对象是只有存在的页面才会存在。因此,有人输入地址 host.com/forum/foo/bar 将收到错误消息“ 404 页面不存在”,而不是空白索引模板。

我正在使用 Symfony 4、Docrine、Twig、Annotations 和其他各种插件

当前代码

 //src/Controller/Controller.php

 /**
 * @Route("/forum/{category}/{slug}", name="page_topic")
 */
public function showTopic($slug){

    $repository = $this->getDoctrine()->getRepository(Topic::class);

    $topic = $repository->findOneBy(['name' => $slug]);



    return $this->render('forum/article.html.twig', ['topic' => $topic]);
}

这是主题页面的控制器,它当前循环主题中的所有线程。但是由于在页面加载之前没有检查 {category} 和 {slug},您可以按字面意思输入任何内容并且不会出现错误,只是一个带有空白部分的模板。(我确实尝试过 {topic} 而不是 {slug} 但由于我无法弄清楚如何处理检查,它会给出错误)

//templates/forum/article.html.twig

{% extends 'forum/index.html.twig' %}

{% block forumcore %}
    <div id="thread list">
        <h4>{{ topic.name }}</h4>
        <ul>
            {% for thread in topic.childThreads %}
                <li><a href="/forum/{{category.name}}/{{ topic.name }}/{{ thread.name }}"><h6>{{ thread.name }}</h6></a></li>
            {% endfor %}
        </ul>
    </div>
{% endblock %}

正如您从 twig 模板中看到的那样,链接依赖于实体的 $name 字段来生成每个页面的 URL,并且是完全动态的。

在此先感谢您,如果您需要更多信息,请在评论中弹出,我可以更新此帖子。

标签: symfony4

解决方案


为了知道当前是否找到了某个项目,URL您只需测试是否$topicNULL

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
* @Route("/forum/{category}/{slug}", name="page_topic")
*/
public function showTopic($slug){
    $repository = $this->getDoctrine()->getRepository(Topic::class);
    $topic = $repository->findOneBy(['name' => $slug]);
    if ($topic === null) throw new NotFoundHttpException('Topic was not found'); // This should activate the 404-page
    return $this->render('forum/article.html.twig', ['topic' => $topic]);
}

推荐阅读