Dependency Injection Container Refactorings, Part Two
This is part of a mini-series about typical refactorings when using DI containers. Read part one.
(c) Jil A. Brown
When configuring objects you will stumble upon occurrences of duplicated configuration. As configuration duplication is as bad as code duplication, making refactorings and maintenance time-intense and error-prone, we try to avoid them. Occurrences I had, started from defining the same hosts over and over for different services and quasi hard-coded upload prefixes for files sprinkled all over my configuration. I will illustrate this refactoring with the image upload example. We configure Zend_File_Transfer and add a few validators to allow image uploads but only specific ones:a€¦ Count a€¦ photoSize a€¦ photoMimeType a€¦ photoImageSize a€¦ photo
When adding validators to Zend_File_Transfer the fourth argument (in this case photo) is the name of the array key of the file. In our case the markup would look like this:
The specific key is important if you allow the upload of various file types in one request. Now we change the requirements and allow not only photos but photos and PDFs (in the same input as photos, so that the user does not need to use different inputs based on file formats). To not mislead the next programmer working on this piece of code, we should change the markup to something like this (give me a better name please):
Now we open our container configuration and change every occurrence of a€ophotoa€¯ to a€ophotoOrPdfa€¯ and hope not to forget one. Except the one you'll find out two month later. To avoid this duplication of configuration, we introduce a parameter and our container configuration changes.photoOrPdf a€¦ Count a€¦ %filePrefix%Size a€¦ %filePrefix%MimeType a€¦ %filePrefix%ImageSize a€¦ %filePrefix%
To make things even more smooth we could inject that parameter into the view and into the controller to make sure, configuration value duplication is no longer an issue with this specific module.
Excluded, as I no longer think this is actually a good idea.
Allow Environment Specific configuration
When you have a development process where you pass several acceptance stages before an artefact goes into production, these stages are typically slightly different from each other. Starting from different service IP addresses over single machine vs. multi machine, there will definitely be some variance among them. Typical variances are:
- Logger settings: severity filters, logging targets like file on development, syslog on the rest
- Database settings master with fake slave a.k.a. read only database user on development, master slave on the rest
- Error handling modes especially for more introspective components: a€oHard faila€¯ vs. a€osoft fail and loga€¯
- Caching: no cachi
Truncated by Planet PHP, read more at the original (another 2946 bytes)