We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

How the DI object instantiate works ?

Hi,

Inside the DI I'll instantiate my tools class like this :

$di->set('tools', function(){
    return new Tools();
});

Then inside my Controller will use

$var1 = $this->tools->myFirstFunction();

But what happened when I call $this->tools twice like this :

$var1 = $this->tools->myFirstFunction();
$var2 = $this->tools->mySecondFunction();

This will instantiate twice new Tools(); ? Or once ? I want to know if it's better to instantiate my object inside the DI or if I have to instantiate my object inside my controller action.

Thanks.



145.0k
Accepted
answer
edited Oct '16

Actually if using in controller there will be used same object no matter if you will use set/setShared.

https://github.com/phalcon/cphalcon/blob/master/phalcon/di/injectable.zep#L119

On first resolve there is tools got from di using magic getter From Phalcon\Di\Injectable which controller extends, and it's added as property. On second accessing it is just using public property = so still same object.

If you want to have IN CONTROLLER each time new object then you need to use it like $this->di->tools->anyFunction(). This will make sure you have new tools each time(as soon as you are not using tools as shared - like setShared or set(..., true)).

Thanks for your answer. In my case I don't want to reinstantiate my tools object. I want to use the same object

edited Oct '16

Then you don't need to do anything at least if you access it using $this->tools in objects extending Phalcon\Di\Injectable.

In some frameworks like Symfony, 'set' is shared by default.

Use:

$di->set('tools', function(){
    return new Tools();
}, true);

or

$di->setShared('tools', function(){
    return new Tools();
});

Yea but read what i wrote. In Injectable case no matter if he set service as shared or not on next accessing it by property name he will always get same object.

Thank you for your answer :)