繁体   English   中英

使用 Symfony 路由的 MVC 路由

[英]MVC routing using Symfony routing

使用symfony/routing,需要为MVC应用实现路由。 禁止使用整个 Symfony,只能使用库。 控制器类:

namespace App\Controllers;
use App\Core\Controller;
class IndexController extends Controller {

    public function IndexAction(){
        $this->View->render('index');
    }

}

查看类:

namespace App\Core;

namespace App\Core;

class View{

    public function render($viewName) {
        $viewAry = explode('/', $viewName);
        $viewString = implode(DS, $viewAry);
        if(file_exists('View/site' . $viewString . '.php')) {
            require 'View/site' . $viewString . '.php';
        } else {
            die('The view \"' . $viewName . '\" does not exist.');
        }
    }
}

和 Index.php 本身,一切都从这里开始:

use App\Controllers\IndexController;

use App\Core\Routing;
use Symfony\Component\Routing\Generator\UrlGenerator;
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;

use App\Core\Application;
use Symfony\Component\Routing\Router;


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

$collection = new RouteCollection();
$collection->add('index', new Route('/', array(
    '_controller' => [IndexController::class, 'IndexAction']
)));

return $collection;

由于通过邮递员向应用程序提出请求,我什么也没有得到,这是什么问题?

在您的前端控制器中,您只是定义路由,而不是实际处理请求,将其与控制器匹配或调用它。

有关于这一主题部分的手册中,它使用了更多的symfony成分,但能有所帮助。

您必须直接从PATH_INFO确定请求的路由,而不是使用HttpFoundation组件,然后尝试将请求与路由匹配。

这是一个非常粗略的实现:

$collection = new RouteCollection();
$collection->add('index', new Route('/', array(
    '_controller' => [IndexController::class, 'IndexAction']
)));

$matcher = new UrlMatcher($collection, new RequestContext());

// Matcher will throw an exception if no route found
$match = $matcher->match($_SERVER['PATH_INFO']);

// If the code reaches this point, a route was found, extract the corresponding controller
$controllerClass = $match['_controller'][0];
$controllerAction = $match['_controller'][1];

// Instance the controller
$controller = new $controllerClass();
// Execute it
call_user_func([$controller, $controllerAction]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM