Static File Version Control in CakePHP

December 7th, 2007 | by useful | in Programming |

One of the problems I’ve had is how to push updates to static files like javascript and content style sheets. If you want to program for performance you have to use a far future expires header to cut down on HTTP requests. The downside to this is that when you update your script and it has the same file name, the users browser wont know that its updated. Entity tags still involve a HTTP request even though the cut down drastically on the data usage.

The tedious way to fix this is to put the version number in the filename and change every layout to link to the new file.

One of the ideas I brainstormed was to add a GET to the URL in each layout that prints out the build/version number. This is an OK fix in that I only have to update my app/config with the new version number but the downside is that the user has to redownload every static file again even if it hasn’t been updated. I could make version numbers for every static file. This is kind of tedious because I have to program a different version number into every layout.

Then it dawned on me that I could override the built in helpers like $javascript->link() and $html->metalink() combined with a simple array with the name of script and the build number to do version control for me.

so a config file like:

$versions = array(’myscript.js’=>’BUILDNUMBER’,'another.js’=>’BUILD2′);

In a layout:

$javascript->link(’my_script.js’)

becomes

<script type=”text/javascript” src=”/js/my_script.js?ver=BUILDNUMBER”></script>

By using a GET the browser is fooled into downloading the file without having to deal with a mess of older files which should be inside some sort of version control system anyway.

I’ll post the code I used later this week when I complete it. If something like this has already been created for CakePHP, I’d like to hear about it.

Tags: | | |

Site RSS Feed | Comment RSS Feed | Trackback.

Leave a Reply

required

required, private