Silex app-> redirect does not match routes

Let my application run on localhost, path: localhost/silex/web/index.php , specific routes, as in the code below, I expect that visiting localhost/silex/web/index.php/redirect redirect me to localhost/silex/web/index.php/foo and displays "foo". Instead, it redirects me to localhost/foo .

I am new to Silex, and maybe I misunderstood everything. Can someone explain where the problem is? Is this behavior correct and should it redirect to absolute paths? Thanks.

 <?php require_once __DIR__.'/../vendor/autoload.php'; use Symfony\Component\HttpFoundation\Response; $app = new Silex\Application(); $app['debug'] = true; $app->get('/foo', function() { return new Response('foo'); }); $app->get('/redirect', function() use ($app) { return $app->redirect('/foo'); }); $app->run(); 
+7
redirect php silex
source share
3 answers

URL redirect expects the URL to be redirect , not the route in the application. Try it like this:

 $app->register(new Silex\Provider\UrlGeneratorServiceProvider()); $app->get('/foo', function() { return new Response('foo'); })->bind("foo"); // this is the route name $app->get('/redirect', function() use ($app) { return $app->redirect($app["url_generator"]->generate("foo")); }); 
+23
source share

For internal redirects that do not change the requested URL, you can also use a subquery:

 use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\HttpKernelInterface; $app->get('/redirect', function() use ($app) { $subRequest = Request::create('/foo'); return $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST, false); }); 

See also Creating Subqueries .

+4
source share

Before "silex/silex": ">= 2.0" built-in tag allows you to create a URL based on the route name.

You can replace:

 $app['url_generator']->generate('my-route-name'); 

By:

 $app->path('my-route-name'); 

Then use it to redirect:

 $app->redirect($app->path('my-route-name')); 

Another possibility is to create a custom direct call forwarding function with a route name:

 namespace Acme; trait RedirectToRouteTrait { public function redirectToRoute($routeName, $parameters = [], $status = 302, $headers = []) { return $this->redirect($this->path($routeName, $parameters), $status, $headers); } } 

Add a tag to your application definition:

 use Silex\Application as BaseApplication; class Application extends BaseApplication { use Acme\RedirectToRouteTrait; } 

Then use it where you need it:

 $app->redirectToRoute('my-route-name'); 
+1
source share

All Articles