Symfony2 routing.yml to external url - php

My question is: How can I generate external url from routing.yml?
I want something similar to:
documentation_product1:
pattern: /my/documentation/product1.php
default: http://www.myothersite.com/product1
Is it possible or something similar?

It is possible to redirect within a controller to an external site
documentation_product1:
pattern: /my/documentation/product1.php
defaults: { _controller: AcmeBundle:Product:show }
// in controller
$this->redirect('http://www.myothersite.com/product1');
But it is not a good practise.
It is better to use the RedirectController from the FrameworkBundle.(mantioned by Paulpro)
Doku:
http://symfony.com/doc/current/cookbook/routing/redirect_in_config.html
https://github.com/symfony/symfony/blob/master/src/Symfony/Bundle/FrameworkBundle/Controller/RedirectController.php

Symfony routes the requested url to a pair of controller and action to execute. It does only internal redirects.
For a redirect to an external URL you need .htaccess and mod_rewrite (if you use apache).

Related

Can I change my custom controller name in Symfony2?

Hi I have a fully functioning Symfony2 application. Now as part of the SEO work I need to change the urls. I am able to change the last part of the url by changing in the routes file. But the string after domain name which is controller name, i can't change.
My current URL: http://example.com/logics/show
Updated URL should be http://example.com/logic/show
I have tried to rename the controller filename and class name. But its not worked.
Please guide me how to change the controller name throughout the application or in URL ?
The easiest way to do a redirect is changing your routing.yml file.
For SEO reasons, you must redirect your old public URLs with a 301, if change is temporal you can do 302, Symfony allow do this easiest, like this example:
redirect_logic_show:
path: /logics/show
defaults:
_controller: FrameworkBundle:Redirect:redirect
route: logic_show
permanent: true
For more info click here

Generate appropriate urls in multiple sub-domain hostname in Symfony2

I am developing a multi sub-domain web application in Symfony 2.
Subdomains:
admin.example.com is the main hosting site.
member.example.com is another sub-domain pointing to same source code.
As mentioned in the documentation here, I configured routing as below :
Parent Routing for member.example.com:
my_app_member:
resource: "#member.yml"
prefix: /
host: "member.example.com"
Note : The above routing is the parent route config for all routes for member.example.com defined in member.yml.
**Now I have anoter route for admin.example.com : **
admin_user_mod:
path: /admin/new
defaults: { _controller: "somecontroller" }
However if I have to generate a full url for the route admin_user_mod using code :
$modLink = $this->get("router")->generate('admin_user_mod');
The generated route path is correct but the base url still stays as member.example.com which should be admin.example.com
Is there an way, or I am missing anything in above route configuration to get the desired results.
OR
Is there any symfony event listener to overwrite router's "generate()" method call?
All your inputs are highly appreciable.
Thank you
Router has getContext() method you can use:
$context = $this->getContainer()->get('router')->getContext();
$context->setHost('admin.example.com');
As it says in the Routing Documentation, passing true as the third parameter for the generate method will generate an absolute URL.
So in your case it would be...
$modLink = $this->get('router')->generate('admin_user_mod', [], true);
Just make sure you specify the host in the route configuration when doing this. So for example your route should be...
admin_user_mod:
path: /admin/new
host: admin.example.com
defaults: { _controller: "somecontroller" }

How to pass a variable to routing defaults in Symfony?

I have a Symfony2 project with multiple brandings (subdomains). Each subdomain should use the same site functions and the same routes (with different hostname). Therefor I want to make the subdomain in the route path to a variable. Now it looks like:
mybundle_route:
resource: "#MyProjectBundle/Controller/"
type: annotation
prefix: /
host: "{subdomain}.%base_host%"
requirements:
subdomain: sub1|sub2
and the routing itself works. But if I try to generate some routes (e.g. in twig), I get following error because no subdomain variable is set:
Some mandatory parameters are missing ("subdomain") to generate a URL for route "company_route".
I don't want to add the parameter to each path() function in the project.
It works perfekt for one subdomain if I add the defaults like this:
defaults:
subdomain: sub1
but the routes are wrong for the other subdomains. Also it doesn't work with
defaults:
subdomain: "%subdomain%"
All I need is to pass the %subdomain% variable to the defaults or to set it somewhere in the controller constructor. But I can't find the way how it is going. I would appreciate any help.
If there is no better solution you could try to set %subdomain% parameter inside configuration file:
Create subdomain_parameter.php inside config folder.
Inside this file you have access to ther $container so you can manually retrieve current subdomain from the url and pass it to the container.
Import subdomain_parameter.php in the config.yml

How to redirect Symfony2 static assets to a controller request?

How can I redirect a static asset in Symfony2 (e.g: JS, CSS or PDF file) to an actual controller action?
I'm trying to redirect this request (this used to represent a static asset which doesn't exist anymore):
http://localsite.dev/bundles/mybundle/misc/attachment.pdf
to this one (local dev site, this request is handled by a controller):
http://localsite.dev/app_dev.php/downloads
or this (live site):
http://livesite.com/downloads
You should be able to just set up a route for it in your routing.yml like any other route,
eg:
my_pdf_route:
pattern: "/bundles/mybundle/misc/attachment.pdf"
defaults: { _controller: MyBundle:PdfController:index }

Routing in Symfony2

How to setup default routing in Symfony2?
In Symfony1 it looked something like this:
homepage:
url: /
param: { module: default, action: index }
default_symfony:
url: /symfony/:action/...
param: { module: default }
default_index:
url: /:module
param: { action: index }
default:
url: /:module/:action/...
I was looking through the cookbook for an answer to this, and think I've found it here. By default, all route parameters have a hidden requirement that they match any character except the / character ([^/]+), but this behaviour can be overridden with the requirements keyword, by forcing it to match any character.
The following should create a default route that catches all others - and as such, should come last in your routing config, as any following routes will never match. To ensure it matches "/" as well, a default value for the url parameter is included.
default_route:
pattern: /{url}
defaults: { _controller: AcmeBundle:Default:index, url: "index" }
requirements:
url: ".+"
I don't think it's possible with the standard routing component.
Take a look to this bundle, it might help :
https://github.com/hidenorigoto/DefaultRouteBundle
// Symfony2 PR10
in routing.yml:
default:
pattern: /{_controller}
It enables you to use this kind of urls: http://localhost/MySuperBundle:MyController:myview
Symfony2 standard routing component does not support it, but this bundle fills the gap Symfony1 left:
https://github.com/LeaseWeb/LswDefaultRoutingBundle
It does what you expect. You can default route a bundle using this syntax:
FosUserBundle:
resource: "#FosUserBundle"
prefix: /
type: default
It scans your bundle and automatically adds routes to your router table that you can debug by executing:
app/console router:debug
Example of automatically added default routes:
[router] Current routes
Name Method Pattern
fos_user.user.login_check ANY /user/login_check.{_format}
fos_user.user.logout ANY /user/logout.{_format}
fos_user.user.login ANY /user/login.{_format}
...
You see that it also supports the automatic "format" selection by using a file extension (html, json or xml).
Here is an example: http://docs.symfony-reloaded.org/master/quick_tour/the_big_picture.html#routing
A route definition has only one mandatory parameter pattern and three optionals parameters defaults, requirements and options.
Here's a route from my own project:
video:
pattern: /watch/{id}/{slug}
defaults: { _controller: SiteBundle:Video:watch }
requirements: { id: "\d+", slug: "[\w-]+"
Alternatively, you can use #Route annotation directly in a controller file. see https://github.com/sensio/SensioFrameworkExtraBundle/blob/master/Resources/doc/annotations/routing.rst
As for the default routes, I think Symfony2 encourages explicit route mapping.
Create a default route is not a good way of programming. Why? Because for this reason was implemented Exception.
Symfony2 is built just to do right things in the right way.
If you want to redirect all "not found" routes you should use exception, like NotFound404 or something similar. You can even customise this page at your own.
One route is for one purpose. Always. Other think is bad.
You could create your own bundle that handled all requests and used URL parameters to construct a string to pass to the controller's forward method. But that's pretty crappy, I'd go with well defined routes, it keeps your URLs cleaner, and decouples the URL and controller names. If you rename a bundle or something, do you then have to refactor your URLs?
If you want to create a "catch all", your best bet would be to hook on the KernelEvents::EXCEPTION event. This event gets triggered whenever an Exception falls through to the HttpKernel, this includes the NotFoundHttpException thrown when the router cannot resolve a route to a Controller.
The effect would be similar to Symfony's stylized 404 page that gets rendered when you send the request through app_dev.php. Instead of returning a 404, you perform whatever logic you're looking to.
It depends... Some of mine look like this:
api_email:
resource: "#MApiBundle/Resources/config/routing_email.yml"
prefix: /
and some look like
api_images:
path: /images/{listingId}/{width}/{fileName}
defaults: { _controller: ApiBundle:Image:view, listingId: null, width: null, fileName: null }
methods: [GET]
requirements:
fileName: .+

Categories