There are many ways to handle image thumbnails. Sites with heavy traffic generate resized copies right after the original image is uploaded. Light traffic sites on the other hand, prefer to wait until the thumbnail is actually requested. Nette offers a few creative ways to handle this:
- You can use .htaccess to catch requests for non-existent thumbnails and redirect them to your script.
- Following the same theme, you can also use your ErrorPresenter to generate the thumbnail and override the response code (so that it’s not 404).
- An unusual solution is to use a helper and generate the thumbnail when rendering your template.
- Or simply use a presenter action.
In any of these cases, you need to decide where you’re going to store the thumbnail and how you’re going to delete/update it when the main image changes. This is where you can use the excellent built-in caching aparatus.
To keep the demonstration simple, I’m going to use the simplest of the pack, a presenter action. This goes into your BasePresenter.
-
span class=”co1″>// a simple database query that returns a single row with the given id
-
‘id’"Entity no longer exists.", 404);
-
// the whole database record is gone
-
// a custom model method that returns full path to the main image file
-
"This entity has no image.", 404);
-
}
-
-
/*
-
* Now the interesting part: storing a thumbnail in NCache
-
*/‘ResizedImages’);
-
// ResizedImages is my own identificator – change to whatever you please
-
-
$cache->clean();
-
// deletes all timed-out/orphaned thumbnails; this call can go into cron instead
-
"|$id|$attribute|${width}x${height}"‘wwwDir’‘+ 2 months’// if the source file changes, clear its cached thumbnail
This is how you then call it from your regular presenter:
-
span class=”st0″>’image_file_name’
Tags: Nette Framework 2.0-beta (revision 8a3182e released on 2011-10-11)