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

setShared service doesn't work

Hi, When i define a service like shared on dependency injector is correct call like:

$di->setShared("MYSERVICE", function(){ return new MYCLASS(); })

$this->MYSERVICE->MYMETHOD

always that i call the construct of my class "MYCLASS" is called again, Why?

thanks!



79.0k
Accepted
answer
edited May '16

Your custom class would only get instantiated on first resolve (i.e. first call from IoC).

Example:

$di->getShared('request'), //fresh instance

//........... code 

//........... code 

//........... code 

//........... code 

//........... more code ...

$di->getShared('request'), //shared instance