Ok, I built a little more robust script:
$DI = new \Phalcon\DI\FactoryDefault();
$DI->set('multi',function(){
return (object)['name'=>'multi','time'=>microtime(TRUE)];
});
$DI->setShared('singleton',function(){
return (object)['name'=>'singleton','time'=>microtime(TRUE)];
});
$DI->setShared('shared',function(){
return (object)['name'=>'shared','time'=>microtime(TRUE)];
});
echo '<pre>';
print_r($DI->get('multi'));
usleep(1000);
print_r($DI->get('multi'));
usleep(1000);
print_r($DI->get('singleton'));
usleep(1000);
print_r($DI->get('singleton'));
usleep(1000);
print_r($DI->getSingleton());
usleep(1000);
print_r($DI->getShared('shared'));
usleep(1000);
print_r($DI->getShared('shared'));
echo '</pre>';
And got this output:
stdClass Object
(
[name] => multi
[time] => 1591049103.716
)
stdClass Object
(
[name] => multi
[time] => 1591049103.7171
)
stdClass Object
(
[name] => singleton
[time] => 1591049103.7182
)
stdClass Object
(
[name] => singleton
[time] => 1591049103.7182
)
stdClass Object
(
[name] => singleton
[time] => 1591049103.7182
)
stdClass Object
(
[name] => shared
[time] => 1591049103.7214
)
stdClass Object
(
[name] => shared
[time] => 1591049103.7214
)
As you can see, the timestamps on the second invocation of both the singleton
and shared
service don't change, showing that the service creation function isn't being called on subsequent calls to get()
.
The important difference between my first and second script is the second script returns an object from the creation function. Phalcon must store that internally - thus if a creation function doesn't return an object, there's nothing to store, so Phalcon calls the function again on subsequent calls to get()
Could you post the code that registers the service and the test code you've written?