具有Symfony组件的自定义框架的路由系统

时间:2014-11-07 17:59:38

标签: php oop symfony routing

enter image description here

我的目录结构如上所示。我正在尝试使用Symfony组件构建一个框架。但有一个问题,当我点击我定义的路线时,它并没有给我回复。

这是我的index.php

<?php

$loader = require 'vendor/autoload.php';
$loader->register();

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

require 'lib/Framework/Core.php';
$request = Request::createFromGlobals();

// Our Framework is now handling itself the request
$app = new Framework\Core();

$app->map('/', function () {
    return new Response('This is the home page');
});

$app->map('/about', function () {
    return new Response('This is the about page');
});

$response = $app->handle($request);

我的Core.php看起来像这样

<?php namespace Framework;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface as HttpKernelInterface;

class Core implements HttpKernelInterface
{
    protected $routes = array();

    public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
    {
        $path = $request->getPathInfo();

        // Does this URL match a route?
        if (array_key_exists($path, $this->routes)) {
            // execute the callback
            $controller = $this->routes[$path];
            $response = $controller();
        } else {
            // no route matched, this is a not found.
            $response = new Response('Not found!', Response::HTTP_NOT_FOUND);
        }

        return $response;
    }

    // Associates an URL with a callback function
    public function map($path, $controller) {
        $this->routes[$path] = $controller;
    }
}

有谁知道这个bug是什么?我搞砸了什么?

1 个答案:

答案 0 :(得分:1)

正如我在评论中提到的,您只是错过了最后一个小细节( - &gt; send()),您告诉Response对象发送标头并回显内容。所以:

$response = $app->handle($request);
$response->send();

而且我认为应该这样做!

干杯!