Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Console output in services #10

Open
jbieliauskas opened this issue Nov 6, 2019 · 0 comments
Open

Console output in services #10

jbieliauskas opened this issue Nov 6, 2019 · 0 comments
Labels
rule Issues related to adding/removing/changing code standard rules

Comments

@jbieliauskas
Copy link
Collaborator

Some commands use services, which require OutputInterface to print messages to console. A common pattern is to do this:

In a service:

class SomeService
{
    public function doSomething(): void
    {
        // code...
        $this->output->writeln('Message');
    }

    public function setOutput(OutputInterface $output): void
    {
        $this->output = $output;
    }
}

And in a command:

class MyCommand extends ContainerAwareCommand
{
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $service = $this->getContainer()->get('some.service');
        $service->setOutput($output);
        $service->doSomething();
    }
}

However, there's nothing special about the $output in a command. The service can instantiate one itself (as does Symfony by just newing-up a ConsoleOutput). This would eliminate the need for a setter, our services would become self-containing, the command would lose extra lines of code.

Furthermore, do not wrap calls to $this->output in a private method if the private method simply forwards a call to $this->output.

❌ This is bad:

class MyService
{
    public function doSomething(): void
    {
        // code...
        $this->doOutput('Message');
    }

    public function doOutput(string $message): void
    {
        $this->output->writeln($message);
    }
}

✅ This is good:

class MyService
{
    public function doSomething(): void
    {
        // code...
        $this->output->writeln('Message');
    }
}
@jbieliauskas jbieliauskas added the rule Issues related to adding/removing/changing code standard rules label Nov 6, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
rule Issues related to adding/removing/changing code standard rules
Projects
None yet
Development

No branches or pull requests

1 participant