ZF2 Dependency Injection – Multiple Object Instances

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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

1
2
3
4
5
6
7
8
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.

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

Produces

1
2
3
4
5
6
7
8
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.

1
2
3
4
5
$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

1
2
3
4
5
6
7
8
object(Test)#9 (1) {
["test":protected]=>
string(9) "some data"
}
object(Test)#11 (1) {
["test":protected]=>
string(9) "some data"
}

 

2 comments
stm
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?

Post Navigation

Web Analytics