How to use a DI container when working with symfony/console commands?

Hi! I’m trying to do a console command to create a user.

I connected symfony/console according to the following example:
https://odan.github.io/slim4-skeleton/console.html

But I don’t understand how to access the ID container inside my command:

Hi Bezlepkin!

If you have followed the guide you linked (Console | Slim 4 Skeleton) all you need to do to get your dependencies is to define a constructor with them.

In your example you could add a constructor like:

	private SomeDependencyClass $someDependency;

	public function __construct( SomeDependencyClass $someDependency)
	{
		parent::__construct();

		$this->someDependency = $someDependency;
	}

And then you can use it inside your execute() function like:

    $this->someDependency->doSomething();

Hope that’s clear and I understood your question!

It works! :grinning:
Why didn’t I think of that myself?! :rofl:

1 Like