Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Silex app->redirect does not match routes

Let my application run on localhost, the path is: localhost/silex/web/index.php, defined routes as in the code below, I'd expect visiting localhost/silex/web/index.php/redirect redirects 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 got it all wrong. Could someone explain where is the problem? Is it correct behavior and it should redirect for 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();
like image 388
user2219435 Avatar asked Mar 03 '14 09:03

user2219435


2 Answers

The redirect url expects an url to redirect to, not an in-app route. Try it this way:

$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"));
});
like image 63
Maerlyn Avatar answered Oct 04 '22 17:10

Maerlyn


For internal redirects, which does not change the requested URL, you can also use a sub-request:

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 Making sub-Requests.

like image 38
Ralf Hertsch Avatar answered Oct 04 '22 16:10

Ralf Hertsch