Symfony Routing Component not routing url



我有像这样的文件夹结构的mvc php cms:

application
---admin
--------controller
--------model
--------view
--------language
---catalog
--------controller
------------------IndexController.php
--------model
--------view
--------language
core
--------controller.php
//...more
public
--------index.php
vendor

我安装了symfony/router组件,以帮助我的路由网址使用作曲家json:

{
"autoload": {
"psr-4": {"App\": "application/"}
},
"require-dev":{
"symfony/routing" : "*"
}
}

现在有了路由文档,我添加了以下代码用于index.php路由:

require '../vendor/autoload.php';
use SymfonyComponentRoutingMatcherUrlMatcher;
use SymfonyComponentRoutingRequestContext;
use SymfonyComponentRoutingRouteCollection;
use SymfonyComponentRoutingRoute;
$route = new Route('/index', array('_controller' => 'AppCatalogControllerIndexControllerindex'));
$routes = new RouteCollection();
$routes->add('route_name', $route);
$context = new RequestContext('/');
$matcher = new UrlMatcher($routes, $context);
$parameters = $matcher->match('/index');

在我的索引控制器中,我有:

namespace AppCatalogController;
class IndexController {
public function __construct()
{
echo 'Construct';
}

public function index(){
echo'Im here';
}
}

现在在行动中,我在这个网址中工作:localhost:8888/mvc/index,看不到结果:Im here索引控制器。

symfony路由URL如何工作并在我的mvc结构中找到控制器? 感谢任何练习和帮助。

请求上下文应填充命中应用程序的实际 URI。与其尝试自己做这件事,你可以使用symfony的HTTP Foundation包来填充它:

use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentRoutingRequestContext;
$context = new RequestContext();
$context->fromRequest(Request::createFromGlobals());

这里也记录了它:https://symfony.com/doc/current/components/routing.html#components-routing-http-foundation

匹配($parameters = $matcher->match('/index');(后,您可以使用参数的_controller键来实例化控制器并调度操作。我的建议是用不同的符号替换最后一个以便于拆分,例如AppControllerSomething::index.

然后,您可以执行以下操作:

list($controllerClassName, $action) = explode($parameters['_controller']);
$controller = new $controllerClassName();
$controller->{$action}();

这应该回显您在控制器类中的响应。

相关内容

最新更新