Question

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();
Was it helpful?

Solution

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"));
});

OTHER TIPS

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.

Up to "silex/silex": ">= 2.0", a native trait allow you to generate an 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 trait to directly redirect 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 the trait to your application definition :

use Silex\Application as BaseApplication;

class Application extends BaseApplication
{
    use Acme\RedirectToRouteTrait;
}

Then use it wherever you need it :

$app->redirectToRoute('my-route-name');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top