1

After attending ZendCon 2012 I saw how a lot of classes in ZF2 that implemented DI and had their dependencies passed to them through the constructor. ZF2 has a Service Manager that helps with this. I'm trying to learn how to implement this and learn its best practices.

And then... I loaded up the ZfcUser module and saw that the User Service was not quite following this pattern, in fact it was hiding it's dependencies behind a bunch of lazy loading getters. Now, this module was initially written by Evan Coury who is the brains behind the whole Module system in ZF2 so I know this particular module is well written or at least follows the suggested zf2 best practices.

My question is, why is this class hiding its dependencies behind getters and actually getting them from the Service Manager (which in this case it looks like it's acting pretty much like a Registry) instead of defining them explicitly in the constructor?

Isn't this in fact going against the DI principle of making dependencies explicit?

4

2 に答える 2

1

I got an answer for this question from Artur Bodera on the Zend Framework mailing list:

It's not against it. It's still an "Inversion of Control" way of doing things, which is a good thing.

ZF2 DI has been in active development in late 2011 and has gained a lot of traction among contributors. At some point though, the performance and config files' complexity became an issue. That's why ServiceManager idea has been brought up.

Up until beta1 (AFAIR) nearly everything was defined in DI and config files were humongous. Applications were slow, memory usage was through the roof, the complexity actually rose as compared to ZF1 Application_Service or similar. There were ideas on how to further optimise DI, but a group of contributors came up with another idea: SM.

ServiceManager allows for more explicit way of building up services. For example, instead of an array of arrays with 20 keys (which is required for DI to be able to handle dependencies correctly and construct objects), you can just use a single factory function/class with a few "new This", "new That" and "return $service" at the end.

There's no strict policy or recommendation against SM nor DI. Both are OK, both have strengths and weaknesses. It's your choice which you'll use. Both are recognised by Zend\Mvc and will be read from you app config.

As for modules - each module's author decides on which method to use. Again - both are valid ways of handling dependencies and automatically constructing instances. Evan chose SM factories in this example.

于 2012-11-14T05:27:34.070 に答える
0

Hopefully Evan will come and explain himself, as he most like will be able to do it much better. My guess is that this is simply because loading up ALL dependencies each time the User-Service is called, simply produces way too much overhead. Therefore the lazy-loading. Most likely that's all there is to it.

于 2012-11-09T21:06:34.897 に答える