nette/di how to pass data to a constructor

Franck
Member | 3
+
0
-

Hi,

here my service nette/Di definition:

services:
latte: \Latte\Engine()
 – App\Lib\MarkdownConverter\MichelfMarkdownConverter()
mc: App\Lib\MarkdownConverter\MarkdownConverter()

I call my service like that

$content = self::$container->getByName(‘mc’);

the question is can I pass an argument to «mc» like $content = self::$container->getByName(‘mc(arg)’);

Marek Bartoš
Nette Blogger | 1173
+
0
-

Values given to a service constructor must be defined in neon

mc: App\Lib\MarkdownConverter\MarkdownConverter('string argument')

If the value is an object, you can just register it as a service and autowiring will pass the object to constructor automatically.

If you want to pass arguments from context, use parametrized factory and register the factory as a service instead https://doc.nette.org/…tion/factory#…

Franck
Member | 3
+
0
-

Marek Bartoš wrote:

Values given to a service constructor must be defined in neon

mc: App\Lib\MarkdownConverter\MarkdownConverter('string argument')

If the value is an object, you can just register it as a service and autowiring will pass the object to constructor automatically.

If you want to pass arguments from context, use parametrized factory and register the factory as a service instead https://doc.nette.org/…tion/factory#…

My issue is that I don't understand the implementation provided in the documentation. I need to use a class in a page controller, so I don't know in advance what argument I will pass to it. I'm forced to use setters to initialize the class after instantiation.

mystik
Member | 291
+
+2
-

If you need to dynamicaly create instances then you cannot degine them statically in DI container. You should define factory service in container and use this factory service to create specific instances when needed.

mystik
Member | 291
+
0
-

You can use generates factories feature to do it https://doc.nette.org/…tion/factory

mystik
Member | 291
+
0
-

Also note that there is only one instance of given service in DI. So if you use setter to modify it you might have unintended side effects if you use it in different places.

Franck
Member | 3
+
0
-

mystik wrote:

Also note that there is only one instance of given service in DI. So if you use setter to modify it you might have unintended side effects if you use it in different places.

ok many thanks.