0

I'm using Sympfony Console as a standalone component.

Let's say I've got a Command defined as follows:

class Box extends Command
{
    public function __construct() {
        // removed for simplicity of this example
    }
    protected function configure() {
        // removed for simplicity of this example
    }
    protected function execute(InputInterface $input, OutputInterface $output) {
        if (!$data=\file_get_contents($input->getOption('inputfile'))) { return false;}
        // rest of code removed for simplicity of this example
    }
}

Obviously it is most likely not correct to use return false; So what is the correct way to do it, I can't seem to find a reference or example in the docs ? The nearest thing I can find is a reference to ConsoleEvents::TERMINATE but using events to achive my goal seems a bit overkill ?

1
  • 1
    just return, no need for the bool i dont think Commented Nov 6, 2019 at 13:31

2 Answers 2

4

For unsuccessful command execution, execute() should return a non-zero integer as error code. See the base class (Symfony\Component\Console\Command\Command) for details.

So just return from your execute() method with the appropriate error code, e.g. return 42;.

The other possibility is to throw an exception, which is automatically caught and formatted by the console component and also causes a non-zero exit code of the command. Whether a regular return or an exception is used depends on the situation. If it's a normal situation (e.g. wrong user input) a regular return is preferrable, in your example (input file not readable) an exception may be adequate as well.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the tip about exceptions!
2

I'd say just return as well, don't know why you'd want to do extra fancy stuff to just terminate the command. You could add an output line before the return to tell what's going on in the cli...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.