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

di->get vs di->getShared

Hello,

if we do setShared(service) then no matter which way we call it get or getShared.

But if we do set(service) then: ->get(service) we always get the new instance ->getShared(service) we always get new instance

Why do we need to have services in DI which always gets new instance? Do you have real life example?

I suggest to keep get() & set() methods as shared services and getFresh() if we really want to get new instance of that service

The same reason one might need both instances and singletons of a class.

Consider this service:

class TimeElapsed {
    protected $_start;
    public function __construct()
    {
        $this->start();
    }

    public function start()
    {
        $this->_start = microtime(true);
    }

    public function print()
    {
        echo round((microtime(true)-$this->_start)/1000), ' seconds elapsed', PHP_EOL;
    }
}
$di->set('elapsed', function() {
    return new TimeElapsed();
});
$elapsed = $this->getDI()->get('elapsed');
sleep(5);
$elapsed->print();
// Should print 5 seconds elapsed

This way you can arbitrarily stack these timers.

edited Mar '19

Why do you need DI for this class? You can do the same just by doing

$elapsed = new TimeElapsed();
sleep(5);
$elapsed->print();

Also you cannot inject anywhere such service:

$di->set('custom.service', function () use ($di) {
    return new CustomService($di->get('elapsed')); // does it looks correct?
});

The same reason one might need both instances and singletons of a class.

Consider this service:

class TimeElapsed {
  protected $_start;
  public function __construct()
  {
      $this->start();
  }

  public function start()
  {
      $this->_start = microtime(true);
  }

  public function print()
  {
      echo round((microtime(true)-$this->_start)/1000), ' seconds elapsed', PHP_EOL;
  }
}
$di->set('elapsed', function() {
  return new TimeElapsed();
});
$elapsed = $this->getDI()->get('elapsed');
sleep(5);
$elapsed->print();
// Should print 5 seconds elapsed

This way you can arbitrarily stack these timers.



8.4k

actually Di::getShared() resolves the service and stores it in Di::_services for future recalls

check the source code @ https://github.com/phalcon/cphalcon/blob/master/phalcon/di.zep



125.7k
Accepted
answer

An example could be a component that connects to a Google account. You pass it along the connection variables when calling get(), in order to be able to connect to multiple different accounts - possibly concurrently.