[英]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組件以使用composer json幫助我的路由網址:
{
"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結構中工作並找到控制器? 感謝您的任何練習和幫助。
請求上下文應使用到達應用程序的實際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}();
哪個應該回顯您在控制器類中的響應。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.