Level-2 / Dice

Dice - a lightweight Dependency Injection Container for PHP
https://r.je/dice
433 stars 68 forks source link

Using a specific instance created by a factory class. #103

Closed antanova closed 8 years ago

antanova commented 8 years ago

I'm using a factory class to create an object, like this:

$webfactory = $dice->create('Aura\\Web\\WebFactory');
$request = $webfactory->newRequest();

I'm then trying to inject $request (that specific instance) into other classes, like so

class WebClass
{
    function __construct(Request $request)
    {
        // do something
    }
}

It seems, from what you say here, using an instance created outside of Dice in this way is impossible. I'm struggling to think of a decent way to work this without changing the dependency to the factory and creating a new instance of Request everywhere it's needed. Am I missing something simple?

edit I should add that I'm using the v2.0-php5.4-5.5 branch

TRPB commented 8 years ago

The solution is the same as on the issue you linked to: Set up the object as a substitution:

$webfactory = $dice->create('Aura\\Web\\WebFactory');
$request = $webfactory->newRequest();
$dice->addRule('WebClass', [
    'substitutions' => [ 
          'Request' => $request
     ]
]);

Alternatively, if you only want the request created when it's needed you can use a function:


$dice->addRule('WebClass', [
    'substitutions' => [ 
          'Request' => ['instance' => function() use ($dice) {
                                $webfactory = $dice->create('Aura\\Web\\WebFactory');
                                $request = $webfactory->newRequest();
          }
     ]
]);
antanova commented 8 years ago

Thanks, I was trying out the closure method, but hadn't realised I could just pass in the instance as in your first example.

Thanks again!