ZF2 Dependency Injection – Multiple Object Instances

2 Comments

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

You will get the following output

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

Produces

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.

prints out

 

2 thoughts on “ZF2 Dependency Injection – Multiple Object Instances

  1. “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?

    1. [email protected], you catch all my little slip-ups.  Fixed

Leave a Reply

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