by Kevin Schroeder | 11:13 am

When you work with the ZF2 Dependency Injection Container (DiC) when you make multiple requests for an instance of an object you will get the same object back each time.

For example, with this code

class Test
{
  protected $test;

  public function __construct($test)
  {
    $this->test = $test;
  }

  public function getTest()
  {
    return $this->test;
  }
}

use Zend\Di\Di;
$di = new Di();

$test = $di->get('Test', array('test' => 'some data'));
var_dump($test);
$test2 = $di->get('Test', array('test' => 'some data'));
var_dump($test2);

You will get the following output

object(Test)#9 (1) {
["test":protected]=>
string(9) "some data"
}
object(Test)#9 (1) {
["test":protected]=>
string(9) "some data"
}

If you provide a different parameter you will get a different object.

$test = $di->get('Test', array('test' => 'some data'));
var_dump($test);
$test2 = $di->get('Test', array('test' => 'some other data'));
var_dump($test2);

Produces

object(Test)#9 (1) {
["test":protected]=>
string(9) "some data"
}
object(Test)#11 (1) {
["test":protected]=>
string(15) "some other data"
}

From this we can conclude that when you are using the DiC that if you request a like object with like parameters you will get the same instance of the object.

But what if you want the injection benefits of the DiC but don’t want to share the object?  Use the DiC’s newInstance method instead with the third parameter being false.  This tells the DiC container to refrain from putting it in the shared object pool.  The get() method does not give you the option of retrieving a non-shared instance and so you will need to call the newInstance() method directly.

$test = $di->get('Test', array('test' => 'some data'));
var_dump($test);

$test2 = $di->newInstance('Test', array('test' => 'some data'), false);
var_dump($test2);

prints out

object(Test)#9 (1) {
["test":protected]=>
string(9) "some data"
}
object(Test)#11 (1) {
["test":protected]=>
string(9) "some data"
}

 

Comments

stm

“Use the DiC’s newInstance method instead with the third parameter being. ” 
Was there supposed to be another word at the end of that sentence? What *is* the false for?

Apr 27.2012 | 04:59 pm

    kschroeder

     @stm Man, you catch all my little slip-ups.  Fixed

    Apr 27.2012 | 07:27 pm

Leave a Reply

Your email address will not be published. Required fields are marked *