Do not use service manager's get() function everywhere in Zend Framework 2

If some model or service is required only in the current scope, avoid usage of $sm->get() because your service will never be destroyed.
Check reference count of the object that is created with $sm->get():

class CronController extends AbstractConsoleController
{
   
    public function updateDomainsAction()
    {
        $updater = $this->getServiceLocator()->get('Backend\Model\UrlsCoverageUpdater');
        debug_zval_dump($updater);
        die;
    }

}

Refcount is 3:


object(Backend\Model\UrlsCoverageUpdater)#643 (4) refcount(3){
  ...
  ["doctrine":protected]=>
  object(Doctrine\ORM\EntityManager)#502 (10) refcount(2){
  ...
The reason of this behavior is that service manager saves service instance (similar to registry pattern).
Any service requested via get() won't be destroyed until request end. Memory usage will constantly grow.
Compare to direct instantiation:

class CronController extends AbstractConsoleController
{
   
    public function updateDomainsAction()
    {
        $updater = new \Backend\Model\UrlsCoverageUpdater;
        debug_zval_dump($updater);
        die;
    }
}
Refcount is 2:
object(Backend\Model\UrlsCoverageUpdater)#643 (4) refcount(2){
  ...
  ["doctrine":protected]=>
  NULL refcount(3)
  ...
But of course no dependencies injected...

The solution. Use $sm->create() instead:

class CronController extends AbstractConsoleController
{
   
    public function updateDomainsAction()
    {
        $updater = $this->getServiceLocator()->create('Backend\Model\UrlsCoverageUpdater');
        debug_zval_dump($updater);
        die;
    }

}

Refcount is 2 and dependencies are injected:

object(Backend\Model\UrlsCoverageUpdater)#643 (4) refcount(2){
  ...
  ["doctrine":protected]=>
  object(Doctrine\ORM\EntityManager)#502 (10) refcount(2){
  ...

Comments

Popular posts from this blog

Memory efficient array permutation in PHP 5.5 using generators

How to dump http request headers with PHP under CGI/FastCGI SAPI

Zend Framework 2 AJAX: return JSON response from controller action. The proper way.