代码之家  ›  专栏  ›  技术社区  ›  user2219435

Silex应用->重定向与路由不匹配

  •  8
  • user2219435  · 技术社区  · 12 年前

    让我的应用程序在本地主机上运行,路径是: localhost/silex/web/index.php ,如下面的代码中定义的路线,我希望访问 localhost/silex/web/index.php/redirect 重定向 我要 localhost/silex/web/index.php/foo 并显示“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();
    
    3 回复  |  直到 12 年前
        1
  •  23
  •   Maerlyn    12 年前

    这个 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"));
    });
    
        2
  •  4
  •   Ralf Hertsch    12 年前

    对于不更改请求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
  •  1
  •   Flo Schild    9 年前

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

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

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

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

    $app->redirectToRoute('my-route-name');
    
    推荐文章