Symfony2上2个控制器之间的路由问题

时间:2016-03-08 16:20:15

标签: php symfony

目前我设置了一个网站,其中包含以下链接(这些是开发链接): -

以下routing.yml设置的这两项工作: -

singlepost:
    path:       /help-advice/{category}/{post}
    defaults:   { _controller: FrontBundle:Posts:singlepost }

livepages:
    pattern:    /{slug}
    defaults:   { _controller: FrontBundle:Pages:livepages }
    requirements:
        slug:   .+

理想情况下,我想更改帮助&建议链接到以下内容: -

因此,我必须将routing.yml更改为: -

singlepost:
    path:       /{category}/{post}
    defaults:   { _controller: FrontBundle:Posts:singlepost }

livepages:
    pattern:    /{slug}
    defaults:   { _controller: FrontBundle:Pages:livepages }
    requirements:
        slug:   .+

由于livepages Controller中允许“/”,这导致列出的两个控制器之间出现问题。如果我访问Meet the Team页面,它会尝试返回singlepost控制器而不是livepages控制器。

任何人都可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

尝试交换此路线。

livepages:
    pattern:    /{slug}
    defaults:   { _controller: FrontBundle:Pages:livepages }
    requirements:
        slug:   .+

singlepost:
    path:       /{category}/{post}
    defaults:   { _controller: FrontBundle:Posts:singlepost }

<强>更新

如果允许/在slug中,这不起作用。

然后,我认为您可以使用Custom Route Loader为每个类别动态注册路由(或动态设置现有的允许值(需求)列表),优先级高于livepages。

或反向解决方案:动态配置livepages路由并设置比singlepost更高的优先级

答案 1 :(得分:1)

定义具有相同要求的两条路线,并且匹配相同的模式没有意义。 你需要在它们之间做出改变(即条件,要求)。

如果你真的需要保持它是实际的,你可以在控制器中进行一些检查以进行(或不进行)重定向。

示例:

public function livepagesAction($slug) 
{
    $em = $this->getDoctrine()->getManager();
    $existingPage = $em->getRepository('Bundle:Page')->findBySlug($slug);

    if (!$existingPage) {
        $parsedUri = explode('/', $slug);

        // If no '/' or less than two route parameters, return a 404
        if (!strpos($slug, '/') || count($parsedUri) < 2) {
            throw $this->createNotFoundException('Route not found');
        }

        // Redirect to the singlepost route 
        return $this->redirectToRoute('singlepost', array(
            'category' => $parsedUri[0],
            'post'     => $parsedUri[1],
        ));
    }

    // Render the view that corresponds to the existing slug.
}

除了singlepost路线中的某些要求(例如参数的特定类型)之外,您还可以根据需要进行调整。

如果涉及两条以上的路线,您可以通过创建EventListener为您完成控制来减轻您的控制权。