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

Question about shared services

Hi All,

I just wanted to know what the difference is between a shared and a non-shared service, is ite merely performance based? What are the best practices?

Lets have a look at an example :

$di->set('commonv', function() {
        $view = new \Phalcon\Mvc\View();       
        $view->setViewsDir(APP_DIR.'/common/views/');        
        $view->setPartialsDir(APP_DIR.'/common/views/partials/');
        return $view;
}, true);

Here we can see that commonv is a shared service, I can access it as follows :

    $di = $this->di->getDefault();
    $commonv = $di->get("commonv");

Any advice much appreciated.

Thanks!



98.9k
Accepted
answer

More than a performance feature, a shared service works as a singleton: https://en.wikipedia.org/wiki/Singleton_pattern

Every time you access a shared service it returns the same instance created the first time the service is accesed:

$request = $di->get('request'); // Creates a request object and returns it
$request = $di->get('request'); // returns the same request object created previously

Non-shared services always returns new instances.

$db1 = $di->get('db'); // returns a new connection
$db2 = $di->get('db'); // returns a new connection