Symfony Routing Component not routing url

Viewed 557

I have mvc php cms like this folder structure:

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

I install symfony/router component for help my route url using composer json:

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

Now with route documents I add this code for routing in 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');

In My IndexController I have :

namespace App\Catalog\Controller;

class IndexController {

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


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

Now in Action I work in this url: localhost:8888/mvc/index and can't see result : Im here IndexController.

How do symfony routing url work and find controller in my mvc structure? thank for any practice And Help.

1 Answers

The request context should be populated with the actual URI that's hitting the application. Instead of trying to do this yourself you can use the HTTP Foundation package from symfony to populate this:

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

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

It's also documented here: https://symfony.com/doc/current/components/routing.html#components-routing-http-foundation

After the matching ($parameters = $matcher->match('/index');) you can use the _controller key of the parameters to instantiate the controller and dispatch the action. My suggestion would be to replace the last \ with a different symbol for easy splitting, like App\Controller\Something::index.

You can then do the following:

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

Which should echo the response you have in your controller class.

Related