Symfony路由组件不路由URL

时间:2018-09-11 07:04:32

标签: php symfony routing symfony4

我有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来获取路线网址的帮助:

{
  "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结构中工作并找到控制器?感谢您的实践和帮助。

1 个答案:

答案 0 :(得分: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}();

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