超简单框架301从Symfony路由重定向

时间:2016-09-05 20:07:00

标签: php symfony symfony-routing

我尝试构建超级简单的框架。我不想使用控制器...基本上一切都很好,这对于简单的网站来说是一个很好的开始,但我还想要一个我遇到问题的功能。

我尝试尽可能简单地使用301重定向添加路由页面。例如,我希望/ facebook与301到http://facebook.com/example

这是我的代码... index.php如下:

<?php

require_once __DIR__.'/../vendor/autoload.php';

$dotenv = new Dotenv\Dotenv(__DIR__.'/../');
$dotenv->load();

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing;

$request = Request::createFromGlobals();
$routes = include __DIR__.'/../routes/web.php';

$context = new Routing\RequestContext();
$context->fromRequest($request);
$matcher = new Routing\Matcher\UrlMatcher($routes, $context);

try {
    extract($matcher->match($request->getPathInfo()), EXTR_SKIP);
    ob_start();
    include sprintf(__DIR__.'/../resources/views/%s.php', $_route);

    $response = new Response(ob_get_clean());
} catch (Routing\Exception\ResourceNotFoundException $e) {
    $response = new Response();
    $response->setStatusCode(404);
    include __DIR__.'/../resources/views/errors/404.php';
} catch (Exception $e) {
    $response = new Response();
    $response->setStatusCode(500);
    include __DIR__.'/../resources/views/errors/500.php';
}

$response->send();

我的routes.php代码:

<?php

use Symfony\Component\Routing;

$routes = new Routing\RouteCollection();

// 200

$routes->add('index', new Routing\Route('/'));
$routes->add('index', new Routing\Route('/about'));
$routes->add('index', new Routing\Route('/contact'));

// 301

// redirect from /facebook to -> http://facebook.com/example
// redirect from /twitter to -> http://twitter.com/example

return $routes;

现在我可以为该路由创建特定文件,就像其他人一样,在该文件中我可以添加标头php重定向...但这是一个繁琐的方法。如何直接在路径内定义重定向?

1 个答案:

答案 0 :(得分:3)

在您的情况下,您可以执行以下操作:

//routes.php

use Symfony\Component\HttpFoundation\RedirectResponse;

$permanentRedirect = function ($url) {
    return new RedirectResponse($url, 301);
};

//...

$routes->add('facebook', new Routing\Route('/facebook', array(
    '_controller' => $permanentRedirect,
    'url' => 'http://facebook.com/example',
)));

//...

return $routes;

接下来,在index.php

//...

try {
    extract($matcher->match($request->getPathInfo()), EXTR_SKIP);

    if (isset($_controller) && isset($url)) {
        $response = call_user_func($_controller, $url);
    } else {
        ob_start();
        include sprintf(__DIR__.'/../resources/views/%s.php', $_route);

        $response = new Response(ob_get_clean());
    }        
} catch (Routing\Exception\ResourceNotFoundException $e) {
    //...
} catch (Exception $e) {
    //...
}