Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create the route in symfony 2 which maps to external URL?

Tags:

php

twig

symfony

Referring to this,

http://symfony.com/doc/current/book/routing.html

we can map url pattern to controller and action

app/config/routing.yml

blog_show:
    path:      /blog/{slug}
    defaults:  { _controller: AcmeBlogBundle:Blog:show }

I want to map the path to external url.

app/config/routing.yml

blog_show:
    path:      /blog/{slug}
    defaults:  "www.example.com/blog"

The requirement is, my current website is in kohana, I am porting it gradually to symfony 2. For my symfony2 app kohana URL are like external urls, I want to configure these urls in routing and use them in standard way,

e.g. in Twig,

<a href="{{ path('blog_show'}}">
  Read this blog post.
</a>

So later on when I port my pages to Symfony, I will have to change only routing file so that I could use same blog_show key to refer to url and I wont' have to change all the files where I have used urls.

like image 629
vishal Avatar asked Jul 26 '13 10:07

vishal


2 Answers

You can do this by using one of the Symfony framework controllers although I'm not sure how this would work with parameters:

blog_show:
    path: /blog/{slug}
    defaults:
        _controller: FrameworkBundle:Redirect:urlRedirect
        path: "http://example.com/blog"
        permanent: true

Note that path: /blog/{slug} grabs the slug directly, but path: "http://example.com/blog/{slug}" doesn't work.

Source: http://symfony.com/doc/current/cookbook/routing/redirect_in_config.html

like image 115
Adam Avatar answered Oct 01 '22 17:10

Adam


As of Symfony 2.2 this is possible by adding the host constraint to the routes:

routing.yml

user_homepage:
  path: /path/to/whatever
  host: "sub.domain.ext"
  defaults: 
    _controller: forExampleAnyNamespaceBundle:Controller:action

There's an official blog post on this issue: http://symfony.com/blog/new-in-symfony-2-2-url-host-support-in-the-routing

like image 34
Fabian Markaban Avatar answered Oct 01 '22 17:10

Fabian Markaban