1

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

我尝试实现尽可能简单的解决方案,以添加带有 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 重定向......但这是乏味的方法。我该怎么做才能直接在路由内部定义重定向?

4

1 回答 1

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) {
    //...
}
于 2016-09-05T20:18:25.287 回答