简体   繁体   中英

How can I have 2 dynamic routes with the same pattern for 2 separate controllers in Symfony2?

I have a blog which generates URLs like:

/article-name
/my-article
/other-article

Then there is a forum with threads using URLs like:

/thread-name
/my-thread
/what-do-you-think

How can I make router to handle this situation? I don't want to use any more URL parameters (like /blog/article-name and /forum/thread-name ). Best way would be first asking blog controller whether there is an article with this URL and if doesn't, ask the forum controller. But how?

The router base on regex, so you can't do that directly. But one solution that might helps you is specify one route to some action which checks if there is an article "some-name" and if it exists redirect (or forward) to ArticleController and if doesn't exist it redirect/forward to ForumController.

You have to define your event listener.

services:
    kernel.listener.subdomain_listener:
        class: Path\To\YourListener\RequestListener
        scope: request
        tags:
           - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }

Then, in your RequestListener you should define onKernelRequest() method and put there your route handling, such as

public function onKernelRequest(GetResponseEvent $event)
{
    if ($event->getRequestType() !== \Symfony\Component\HttpKernel\HttpKernel::MASTER_REQUEST) {
        return;
    }

    //... check if article exists, otherwise forward to blog controller
}

For additional information about event listeners you could refer to the documenation:

http://symfony.com/doc/current/cookbook/service_container/event_listener.html
http://symfony.com/doc/2.0/cookbook/doctrine/event_listeners_subscribers.html

You can use controllers' redirecting functionality . For example:

//BlogController.php

public function indexAction ($articleName) {
    // ...
    // If article $articleName exists
    if ($article = $repo->findOneByName($articleName) {
        // ...
    // else let the forum controller handle request
    } else {
        return $this->redirect($this->generateUrl('forum_index', array('articleName' => $articleName)));
    }
    // ...
}

There is a bundle which allows chained routing:

http://symfony-cmf.readthedocs.org/en/latest/reference/routing-extra.html

somebody recommended it to me in a symfony2 mail conversation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM