[英]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.