How can I run symfony 2 run command from controller

前端 未结 9 1435
长发绾君心
长发绾君心 2020-11-28 20:03

I\'m wondering how can I run Symfony 2 command from browser query or from controller.

Its because I don\'t have any possibility on hosting to run it

9条回答
  •  攒了一身酷
    2020-11-28 20:16

    If you have to pass arguments (and/or options), then in v2.0.12 (and may be true for later versions), you need to specify InputDefinition first before instantiating an input object.

    use // you will need the following
        Symfony\Component\Console\Input\InputOption,
        Symfony\Component\Console\Input\InputArgument,
        Symfony\Component\Console\Input\InputDefinition,
        Symfony\Component\Console\Input\ArgvInput,
        Symfony\Component\Console\Output\NullOutput;
    
    
    // tell symfony what to expect in the input
    $inputDefinition = new InputDefinition(array(
        new InputArgument('myArg1', InputArgument::REQUIRED),
        new InputArgument('myArg2', InputArgument::REQUIRED),
        new InputOption('debug', '0', InputOption::VALUE_OPTIONAL),
    ));
    
    
    // then pass the values for arguments to constructor, however make sure 
    // first param is dummy value (there is an array_shift() in ArgvInput's constructor)
    $input = new ArgvInput(
                            array(
                                    'dummySoInputValidates' => 'dummy', 
                                    'myArg2' => 'myValue1', 
                                    'myArg2' => 'myValue2'), 
                            $inputDefinition);
    $output = new NullOutput();
    



    As a side note, if you are using if you are using getContainer() in your command, then the following function may be handy for your command.php:

    /**
     * Inject a dependency injection container, this is used when using the 
     * command as a service
     * 
     */
    function setContainer(\Symfony\Component\DependencyInjection\ContainerInterface $container = null)
    {
        $this->container = $container;
    }
    
    /**
     * Since we are using command as a service, getContainer() is not available
     * hence we need to pass the container (via services.yml) and use this function to switch
     * between conatiners..
     *
     */
    public function getcontainer()
    {
        if (is_object($this->container))
            return $this->container;
    
        return parent::getcontainer();
    }
    

提交回复
热议问题