Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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!



85.3k
Accepted
answer

More than a performance feature, a shared service works as a singleton: http://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