using the class name as key in the DI container
In ZenMagick there is a convention that the key to request a class instance from the DI container is to be the class name of the implementation expected.
This is not quite in line with other projects and I’d like to briefly outline why things are as they are.
The migration from the prefix based class resolution to a container based dependency injection system is a long one. With the old system the loader would take care of deciding which class to instantiate. Now, the dependency container needs to know all sorts of things before it can do that. Most importantly, though, it won’t work if there is no default configured.
Now, to avoid having to build a exhaustive DI config file right away I decided that by using the class name as the key, the container can default to implementing an instance based on the key if no definition is found. This means all code can start using the container and once a definition is there it will be used. If not – the default will be used.
The only downside of this system is that it is not possible to guess the scope (prototype/container). To fix this during the migration time a method getService() was added to the container class that guarantees that the returned instance is a singleton with container scope.
I expect that this method will disappear with the next or second next release, so do not rely on it. Deprecating and removing this method will require to add definitions for at least all classes used for those getService() calls.
In addition to the above we will be adding aliases for defined services, so eventually the lookup can be done either way. However, use of the alias is the preferred style.
The main advantage of aliases (or, better, symbolic keys in general) is that it decouples the lookup from the actual class (even the default one). Seeing that we are planning on using PHP namespaces throughout the codebase, not using the alias might eventually break things, once the default class has changed name.
Having said that, the code to default to the key as class name is not going to disappear in the foreseeable future as it is useful in itself, even if aliases are to be used for known services.
UPDATE: One other thing that just occurred to me is that with symbolic names it is possible to use them in bean definitions as well. Good news because that will obsolete a few more settings that deal with implementation classes and will make the code using those definitions much simpler.
