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

Reuse instance? #7

Open
kenjis opened this issue Feb 8, 2014 · 6 comments
Open

Reuse instance? #7

kenjis opened this issue Feb 8, 2014 · 6 comments

Comments

@kenjis
Copy link

kenjis commented Feb 8, 2014

Each time we get an object, di returns a new instance of it.

How about adding a way to get the same instance to be returned for all calls?

@dongilbert
Copy link
Member

Are you using build or resolve to get your dependencies?

@dongilbert dongilbert reopened this Feb 8, 2014
@dongilbert
Copy link
Member

Sorry, accidentally closed. I meant what are you using to get your objects.

@kenjis
Copy link
Author

kenjis commented Feb 8, 2014

Yes, I'm using resolve.

Is there any methods to get my objects?

@kenjis
Copy link
Author

kenjis commented Feb 8, 2014

And what if I want to get the same instance in Automatic Dependency Resolution?

@adriengibrat
Copy link

Hello,
There is no method share or singleton like in other well known DI at the moment.

But you can do like this:

$container = new League\Di\Container;
$container->bind('\League\Di\Stub\Bar');
$container->extend('\League\Di\Stub\Bar', function ($container, $instance) {
    static $singleton;
    if (is_null($singleton)) {
        $singleton = $instance;
    }
    return $singleton;
});
// This will return the same Bar instance on each call
$container->resolve('\League\Di\Stub\Bar');

I there was in resolve method a check like:

if ($rawObject instanceof \Closure || $rawObject instanceof Definition) {
    return $rawObject();
}
return $rawObject;

You could also do

$container->bind('\League\Di\Stub\Bar', $instanceOfBarAlreadyExisting);
// This will return the $instanceOfBarAlreadyExisting instance on each call
$container->resolve('\League\Di\Stub\Bar');

Would you like a PR with proper unit tests?

@kenjis
Copy link
Author

kenjis commented Feb 11, 2014

@adriengibrat Thank you for your explanation.

But I still want a short way, so I sent PR as a trial. #8

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants