Symfony 4 使用 URL 检查数据库是否存在页面 else 404

Symfony 4 use URL to check database if page exists else 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,并且是完全动态的。

提前致谢,如果您需要更多信息,请在评论中弹出,我可以更新此 post。

为了知道是否在当前 URL 找到了一个项目,你可以测试 $topic 是否是 NULL

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]);
}