auraphp / Aura.Di

Dependency Injection System
MIT License
349 stars 63 forks source link

Aura Input Options is getting the closure #40

Closed ghost closed 10 years ago

ghost commented 10 years ago

Paul,

Correct me if I'm wrong, but today at work I saw something that might be wrong. The code:

<?php

$di->params['Aura\Input\Form'] = [
   'builder' => $di->lazyGet('builder'),
   'filter' => $di->lazyGet('filter'),
   'options' => [
         'helperList' => $di->lazyGet('helperList')
   ]
];

The options key in the constructor injector will receive an array containing N available options, but the lazyGet('helperList') returns the callable. Shouldn't it be returning the object?

In this example I've set the params to Aura\Input\Form, but locally it's mapped to a final Form class.

harikt commented 10 years ago

lazyGet always will get callable. Instead use lazyNew here.

harikt commented 10 years ago

aah there is another thing I am seeing. It may also depends on how your lazyGet is asked to call.

Example I tried

class Example
{
    public function __construct(Foo $foo) 
    {
        echo get_class($foo);
    }
}

class Foo
{
}

$di = new Container(new Forge(new Config));
// 1 ) $di->set('lazyfoo', new Foo);
// 2 ) $di->set('lazyfoo', $di->lazyNew('Foo'));
$di->params['Example'] = [
    'foo' => $di->lazyNew('Foo')
    // for 1, 2 comment the above line and uncomment the below line
    // 'foo' => $di->lazyGet('lazyfoo')
];
$di->newInstance('Example');
ghost commented 10 years ago

Hari,

In our case, the helperList is a service, defined this way:

$di->set('helperList', function() use ($di) {
   return $di->newInstance('app\services\HelperList');
});

We use lazyGet a lot with our constructor params and we always get the reference, except at this time.

The lazyNew in this case, will return an instance, but we always define our services using the way described above, in case we need to do any setup before returning the instance.

harikt commented 10 years ago

I feel lazyGet is working as expected. Ping @pmjones for further details.

pmjones commented 10 years ago

I think the problem here is that the 'options' key is presented as an array, and the DI container does not descend to array elements to resolve lazy objects. If you modify it to be something more like this ...

'options' => $di->lazyGet('helperList')

... then the form $options will be your helperList service object.

Let me know if that helps.

ghost commented 10 years ago

Paul and Heri, sorry for the late update. Yes, using with arrays doesn't work as expected and we've already eliminated the array.

Thanks!

pmjones commented 10 years ago

:+1:

harikt commented 10 years ago

@ramirovjr :+1: .

NB : H A RI ;)