Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to call class functions using Symfony's router and http-foundation components?

Tags:

php

symfony

I've recently plugged Symfony's Routing and HttpFoundation components into my legacy app, and I'm slowly starting to convert all of my code over.

Everything's working surprisingly well so far, but I think I'm heading down a rabbit hole with the way I've structured my controllers and the way the router calls them. Here is some of the code located in my front controller:

// look up the controller and action defined in routes.yml
$parameter = $router->match($request->getPathInfo());

// call the action and get the output
$output = call_user_func('MyCompany\\Controller\\' . $parameter['_controller']);

// send the output in the response and so forth
// ....

So, the call_user_func line would actually call something like MyCompany\Controller\GeneralController::indexAction, which ultimately returns the html output, which is sent in the response.

Because of the way I have everything set up, I have to use statements like return self::display('filename.tpl');. This seems wrong to me. Is there a better way to call these controller actions?

like image 828
Nick S. Avatar asked Dec 01 '25 18:12

Nick S.


1 Answers

You'll probably want to use ControllerResolver. Or you might want to use HttpKernel more directly, which does the resolution for you.

If you use the ControllerResolver, it will create a "callable", and also fetch the arguments you can do $response = call_user_func_array($controller, $arguments);

There are a lot of other benefits to using the HttpKernel or AppKernel, which provide a lot more scaffolding.

like image 146
Daniel Avatar answered Dec 04 '25 06:12

Daniel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!