I want to perform an action from a custom command. The forward method Controller.php class provides this function, but I do not know access it from the execute () method of the command file
问题:
回答1:
Making the controller a service will result in performance overhead because of the request stack, as it then should return a HttpResponse
. The Request
scope will not be very usefull in the command.
I'd advise you to refactor the action from the Controller to a separate service class definition, and get that class from the container in both the controller and the command by making it a ContainerAwareCommand
.
http://symfony.com/doc/current/cookbook/console/console_command.html#getting-services-from-the-service-container
回答2:
Use controller as service How to Define Controllers as Service
回答3:
If you're trying to call a controller action from a command then you'll need to set up the controller (and subsequently the request for the controller) in your command code.
If you have a look in Symfony\Bundle\FrameworkBundle\Controller
then you'll see that the forward()
method duplicates the current Request
object and then sends it through the HttpKernel
. As Commands don't use HttpKernel, this kind of forwarding won't work.
Depending on what your action does, you might just be able to do:
$controller = new Your\Controller();
$controller->yourAction();
If your action requires a request then:
$request = Symfony\Component\HttpFoundation\Request::createFromGlobals();
$controller = new Your\Controller();
$controller->setContainer($this->getContainer()); // from the ContainerAwareCommand interface
$controller->yourAction($request);
By the sounds of it this isn't going to do what you want so there are a couple of ways forward:
- Turn your controller into a service, this is described in the cookbook and will mean that your controller and action can be summoned directly from the container that your command (probably) has set up. This handles dependencies that your controller and actions may have.
- Split out the functionality that you need from your action into its own class or service. This is the better way forward as if you're calling the same bit of code in two places it makes sense to centralise it somewhere.