Zend 2:我可以向路由器公开多少钱?

I have a best practices question relating to building a custom router in Zend 2. I would like to use the service manager to get something in my router which would allow me to connect to an arbitrary data source (without exposing any info to my router) so that I can determine whether or not I can match that route.

For example, I would do something like this in my match() method:

$serviceManager->get('site_manager')->locateByRequest($request);

However, there isn't a clear way to access the service locator in a router. I found this article which essentially creates a custom factory so that you inject the service locator into your router: http://www.zendexperts.com/2012/12/09/custom-routing-in-zend-framework-2/

Is this the best way to do this? Are there any other ideas or suggestions?

The main thing here is to NOT allow my router to know anything about the implementation of my so-called site_manager which may use a JSON text file, or MongoDB backend, or anything else for that matter. I want no dependencies and I want to expose no more than the method call from my above code example.

Ideas, comments, suggestions?

I think that injecting the whole service manager is just too much. I think it is ok to inject it in contollers, or in other helpers than could need to access many services, but for a helper component with a responsability as defined and as narrow as the router, i would prefer to:

  • create an interface, that defines what behavior should have the class that the router will work with.
  • inject just the service that the router needs, that could be any class implementing that interface.

With this, you can change the behavior of how the router resolve routes, changing the service that you are using to do it, but without having to change the routers code to access to something that should not be more than a configuration issue. With this you will get a better decoupling and have a more pure dependency injection.

Take a look at this article about Service Locator, Dependency Injection, and their differences

Also, it can be also interesting to take a look at the Strategy Pattern . This is more or less what im talking about. Instead of giving the router the knowledge and the ability to decide, it is just expecting a dependency to be injected, and inside that dependency is the implementation of some processes that the router needs, but which strategy to achieve the same result could be different, and the router doesn't really care about which one is being used.