Symfony Routing Component不路由URL

问题描述 投票:2回答:1

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

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

我使用composer json安装symfony/router component来帮助我的路由url:

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

现在使用路线文档,我在index.php中添加了此代码以进行路由:

require '../vendor/autoload.php';
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;

$route = new Route('/index', array('_controller' => 'App\Catalog\Controller\IndexController\index'));
$routes = new RouteCollection();
$routes->add('route_name', $route);

$context = new RequestContext('/');

$matcher = new UrlMatcher($routes, $context);

$parameters = $matcher->match('/index');

在我的IndexController中,我有:

namespace App\Catalog\Controller;

class IndexController {

    public function __construct()
    {
        echo 'Construct';
    }


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

现在我在使用这个url:localhost:8888/mvc/index并且看不到结果:Im here IndexController。

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

php symfony routing symfony4
1个回答
0
投票

应使用实际的URI来填充请求上下文。您可以使用symfony中的HTTP Foundation软件包填充此代码,而不是尝试自己执行此操作:

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\RequestContext;

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

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

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

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

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

哪个应该响应您在控制器类中的响应。

© www.soinside.com 2019 - 2024. All rights reserved.