thephpleague / container

Small but powerful dependency injection container

Home Page:http://container.thephpleague.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to pass argument to get() in v3

texelate opened this issue · comments

In v2 you could pass arguments as the second parameter to get():

$container->get($reference, $args);

But it seems in v3 the function is just:

get($id, bool $new = false)

How do I pass arguments on the fly when getting an object in v3?

Thanks!

v3 implements the PSR ContainerInterface where the get method can't really allow for runtime arguments, I'd also been looking at removing it anyway as it encourages service location rather than dependency injection proper.

However, there is a way to achieve this.

$container->add(Example::class); 
// notice no args set on the definition, however, if your 
// args aren't likely to change, it is better to do it where 
// you define dependency definitions
$container->extend(Example::class)->addArguments($args);

$resolved = $container->get(Example::class, true);

Thanks, Phil. Based on your example then and my use case I think in my wrapper I am better add()ing and share()ing each object explicitly rather than trying to reuse ones and pass arguments as I did in v2.

By the way, what does $new do in get()? Haven’t you already declared it shareable or not shareable by this point via add() or share()?

Thanks again for this.

the $new flag will create a new instance regardless of whether it is defined as shared or not

Great, thanks again Phil!