S
S
slip312019-12-11 12:55:56
symfony
slip31, 2019-12-11 12:55:56

And how to work with Symfony Routing as a separate component?

Good afternoon. I wanted to add routing from Symfony to my project.
I read the documentation , started to do it (without annotations, since for them, obviously, you need to install the symphony itself) and something I'm stupid further
The same algorithm, right?
1) I write the routes themselves and bind the controllers

$routes = new RouteCollection();
$routes->add('home', new Route('/', ['_controller' => [HomeController::class, 'index']]));
$routes->add('article', new Route('/article', [ '_controller' => [ArticleController::class, 'index']]));

2) Next do
$context = new RequestContext();
$request = Request::createFromGlobals();
$context->fromRequest($request);
$matcher = new UrlMatcher($routes, $context);
$parameters = $matcher->match($request->getPathInfo());
  //       print_r($parameters);

All OK. If on the main page, then print_r gives
Array ( [_controller] => Array ( [0] => App\controllers\HomeController [1] => index ) [_route] => home )

on site/article
Array ( [_controller] => Array ( [0] => App\lib\ArticleController [1] => index ) [_route] => article )

On those that are not, it gives out
ResourceNotFoundException: No routes found for ..., which is also, in general, correct.
And what should directly translate to the controller? What did I miss?
class HomeController {

    public function __construct() {
        $this->actionIndex();
    }

    public function index() {
        print_r('Home Controller');      
    }

}

Doesn't output "Home Controller".
What did I miss?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BoShurik, 2019-12-11
@slip31

It already depends on your application.
You can, for example, use https://github.com/PHP-DI/Invoker, there will be something like

$parameters = $matcher->match($request->getPathInfo());
$invoker = new Invoker\Invoker(null, $container);
$invoker->call($parameters['_controller'], $parameters);

If without a container, then something like
$parameters = $matcher->match($request->getPathInfo());
list($class, $action) = $parameters['_controller'];
unset($parameters['_controller']);
$controller = new $class;
$controller->$action($parameters);

But passing arguments through an array is not very convenient.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question