Question

I'm building a ZF2+mongoDB+Doctrine ODM app.

I'm trying to use some patterns, and I need for Documents to be able to fetch other Documents from the database.

My problem is that I can't get a DocumentManager instance inside a Document. I can only get it inside a controller.

I wish to avoid having to pass $dm as a parameter to every model down the line of the factories.

Could you guide me to be able to get the ODM Document Manager inside my models?

Thanks!

Was it helpful?

Solution

Actually, you shouldn't get documentManager inside a document. Always get DM via ServiceLocator and use it in your Services/Models/Controllers. Persisting documents via DM on controller level is not a good practice. Controllers should consume related service/model interfaces to do that.

For your question, models and/or services should implement ServiceLocatorAwareInterface and properly configured to use SM.

If you need DM in every service/model instance, simply write a factory or initializer for that. Form the documentation:

Initializers : You may want certain injection points to be always called. As an example, any object you load via the service manager that implements Zend\EventManager\EventManagerAwareInterface should likely receive an EventManager instance. Initializers are PHP callbacks or classes implementing Zend\ServiceManager\InitializerInterface. They receive the new instance, and can then manipulate it.

Also this SO answer explain details how to do that (getting EM in services) with EntityManager but logic would be same for DocumentManager.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top