I think it's better to use constructor, if possible.

What's the difference in getting services in initialize via $this->getHelper('container'), as in translation-extract (https://github.com/…tCommand.php#…)?

What's the best practices then?

There was no “better” way before. And yes, you're right, constructor injection is the best (and It would have worked in the past), but then again, there were other issues.

Every time you run cli, for example even listing of commands… $ php www/index.php … every single service that is passed to the commands via constructor will be initialized. Having >20 commands means probably initializing >80% of your object graph just to show the list of available commands.

So there should be a compromise probably…

class MyCommand extends Symfony\...\Command
    /** @var \My\Dependency @inject */
    public $dependency;

current Kdyby/Console disables injects on all commands for compile-time and calls them manually if and only when the command is invoked

You can use constructor injection if you preffer to initialize a large portion of your object graph, but then again, you don't have to… :)

  • Comments:

  • Hmm… what about Kdyby/Autowired? This seems to be nice place to use it.

    by Jáchym Toušek at 12.7.2014 1:33

That's pretty smart :). I'm taking @inject way

Thank you for explaining.

I just realised by circumventing constructor (unserialize) it would be possible without @inject hack. If commands are properly written there should not be an issue.

I don't think I wanna support such use-case.

You must first log in to participate in this discussion