It’s a common one. You have a project that requires uploaded images. These images need to be displayed in different layouts at different sizes based on the context (ex: large on a detail page, thumbnail on the list page, etc…) In the past I would have encapsulated these sizes in an image class and implemented the resizing to happen at upload time.
The problem pops up when the layout changes. You (or someone else) decides that the thumbnail need to be bigger. You go into your code – say it’s in a class called Image. Your image class has methods like, resizeAndInstallThumbnail(), getThumbnailUrl(), etc… Like a good little OO programmer you’ve hidden the actual dimensions of the thumbnail in the class. So you change those and you’re all set.
Well… sort of. You forget that you used getThumbnailUrl() in another layout, and that one wasn’t supposed to change. After breaking the other layout severely you fix the problem by adding a method like getSearchResultThumbnailUrl(). Annoying, but not so bad. But, wait. You forgot this site is in production, with hundreds of uploaded images that all need to be resized. If your app has been storing the original uploaded files then you can write a one-off script to regenerate the resized images. If not, it’s time to re-upload all your images.
The real problem here is that the rate of change in the presentation layer is high. And we’ve coupled some lower-level infrastructure to that presentation by designing our api around it with method names like getThumbnailUrl(). “Thumbnail” is a presentation word. Why does the object responsible for uploads and resizing need to know what a “SearchResultThumbnail” is? Why not have the presentation layer talk to the image infrastructure layer in a more generic way… Like pixel dimensions? Here’s what you end up with:
<img src="<?php echo $image->getUrlByHeight(55); ?>" alt="Product Thumbnail"/>
The benefit here is that the hard-coded pixel values now appear in the presentation layer, where they belong. In addition, you can easily resize the images on demand. If you add new sizes to your layout, all you have to do is specify the new dimensions and any new images files will be generated as needed.
My brother Jay came up with this idea. I’m sure others out there are using similar techniques, but there was something about the simplicity of his solution that really appealed to me.