【问题标题】:Symfony Routing not making senseSymfony 路由没有意义
【发布时间】:2016-05-12 21:10:08
【问题描述】:

我正在自学 Symfony。而且路由没有任何意义。

我有一个 postController 类,其中包含一些操作。最初命令行中的 crud 生成器给了我这个;

/**
 * Post controller.
 *
 * @Route("/post")
 */
class PostController extends Controller
{
    /**
     * Lists all Post entities.
     *
     * @Route("/", name="post_index")
     * @Method("GET")
     */
    public function indexAction()
    {
        //
    }

    //
}

我想要实现的是从类本身中删除@Route。因此,我希望我的indexAction 成为主页,并且我班级中的所有其他操作仍以/post 开头。比如这就是我想要的;

class PostController extends Controller
{
    /**
     * Lists all Post entities.
     *
     * @Route("/", name="homepage")
     * @Method("GET")
     */
    public function indexAction()
    {
        //
    }

    /**
     * Finds and displays a Post entity.
     *
     * @Route("post/{id}", name="post_show")
     * @Method("GET")
     */
    public function showAction(Post $post)
    {
        //
    }

    // what I want for the showAction should count for all other Actions as well
}

当我进行更改时出现错误;

找不到“GET /post/”的路由

有人可以向我解释我做错了什么以及如何解决这个问题。我不认为这是大事,可能是我看不到的小事。我想让indexAction 成为我的主要操作,即用户登录后网站打开时的操作。谢谢

【问题讨论】:

    标签: php symfony


    【解决方案1】:

    您的路由规范需要{id} 参数,这是强制性的,因此确实没有"GET /post/" 路由。您需要执行以下操作之一

    1. 例如传递id 值并访问/post/1
    2. 从路由规范中删除{id},然后您可以访问/post/
    3. 传递id 的默认值,这样您就可以访问/post//post/1。为此,您的路线规范应类似于 @Route("post/{id}", name="post_show", defaults={"id" = 1})

    【讨论】:

    • 不是那条路线的问题,也不是行动的问题。我知道这一点,我只是在这里快速做了一些事情,以便向您展示这个想法。但是,是的,我知道,这可能会导致理解不清(仍然会在问题中解决它)。更多的是关于indexAction()。由于某种原因它现在可以工作,我想我忘了尝试清除缓存......
    【解决方案2】:

    找不到"/post/" 的正确路径

    因为没有路由"/post/" 在您的示例中,只有 "/""/post/{id}"

    所以这很有意义,我更喜欢使用 yml 符号和前缀,所以它不绑定到一个类

    检查DOCS中的“YAML”标签

    【讨论】:

    • 我知道"/post/" 没有路由,但为什么 Symfony 说有呢?但没关系,由于某种原因,它现在可以工作了。我继续做其他事情并为此清除缓存,后来我看到路由也正常工作,所以我猜是必须清除缓存。我以为我确实尝试过....
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-17
    • 2018-01-26
    • 2017-07-02
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多