2014-03-03 34 views
7

讓本地主機上我的應用程序運行,路徑爲:localhost/silex/web/index.php,定義路由作爲在下面的代碼,我期望訪問localhost/silex/web/index.php/redirect重定向localhost/silex/web/index.php/foo並顯示「富」 。相反,它將我重定向到localhost/fooSilex的APP->重定向不匹配的路由

我是新來的Silex,也許我錯了。有人可以解釋問題在哪裏嗎?這是正確的行爲,它應該重定向絕對路徑?謝謝。

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

回答

23

redirect url需要url重定向到,而不是應用內路由。試着這樣說:

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

坦克你的解釋,將使用此:

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

那麼無論你需要它使用它! :) – user2219435

+0

是否可以從POST請求重定向到GET? – Fractaliste

+0

是的,實際上如果你重定向,下一個請求將是GET,http規範定義了這一點。 – Maerlyn

4

對於內部重定向,這不會改變請求的URL,你也可以使用一個子請求:

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

Making sub-Requests見。

+0

我知道子請求的,我只是想我能做到這種方式。感謝你的回答。 – user2219435

1

截至"silex/silex": ">= 2.0",本機特徵允許您根據路由名稱生成一個URL。

您可以更換:

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

通過:

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

然後用它來重定向:

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

另一種可能性是創建一個自定義特性直接與重定向路線名稱:

namespace Acme; 

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

添加特性到你的應用程序定義:

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

標量類型提示僅適用於PHP7。你最好從你的片段中刪除它們。 – Trix