【问题标题】:Silex app->redirect does not match routesSilex app->redirect 不匹配路由
【发布时间】:2014-04-04 06:23:16
【问题描述】:

让我的应用程序在 localhost 上运行,路径是:localhost/silex/web/index.php,在下面的代码中定义路由,我希望访问localhost/silex/web/index.php/redirect 重定向我到localhost/silex/web/index.php/foo 并显示'富'。相反,它会将我重定向到localhost/foo

我是 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();

【问题讨论】:

    标签: php redirect silex


    【解决方案1】:

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

    【讨论】:

    • 谢谢你的解释,会用这个! :)
    • 是否可以从 POST 请求重定向到 GET 请求?
    • 是的,实际上如果你重定向,下一个请求将是GET,http规范定义了这个。
    【解决方案2】:

    对于不改变请求 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

    【讨论】:

    • 我知道子请求,我只是认为我可以这样做。感谢您的回答。
    【解决方案3】:

    直到"silex/silex": "&gt;= 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);
        }
    }
    

    将特征添加到您的应用程序定义中:

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

    然后在需要的地方使用它:

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

    【讨论】:

    • 标量类型提示仅在 PHP7 中可用。您最好将它们从您的 sn-ps 中删除。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-05
    • 2013-01-18
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多