Versioning Your Resource Files in CakePHP

If you have AJAX interactions on your page, or recently went through a style overhaul in your application you’ve probably run into the problem of users having cached versions of resource files. Instead of forcing your users to clear their cache, you can version your resource files! This is easy to implement and saves you time down the road. If you make frequent changes to your JavaScript, CSS, or other resource files I recommend you follow along!

Where to Put Our Version

First we have to store our version number somewhere. This number will have to be incremented when you make changes to your resource files.

We will put our version number in the AppController so we can access it in all views. Hopefully, you have all of your resource files in the header or footer of your page, but sometimes it’s necessary to have a script only load on one page. I don’t judge.

We put our version in the beforeFilter function of our AppController and set the version number as a view variable that can be accessed in any view.


public function beforeFilter(EventInterface $event) {
	$version = "1.0.0";

Now we have to use the version number to tell the browser which version of the resource to load.

How to Version Resource Files

In order to version our files we will append the version number after the filename.

The format is filename.xx?=$version. Let’s look at an example:


<link rel="stylesheet" href="mystyle.css?=<?= $version ?>">
<script src="app.js?=<?= $version ?>"></script>

You can see that our resources are now versioned! What if we don’t want to increment our version by hand every time we update one of our resource files?

CI/CD and Versioning

CI/CD, Continuous Integration, and Continuous Development are methodologies for automating the building, testing, and deployment of our applications. Whether you’re using a Perl script to run tests and push changes to GitHub if enough of them pass, or you have an on-prem Jenkins server updating the version number is pretty simple.

  1. Move the version number into the config
  2. Load that version from the config in the beforeFilter of our AppController
  3. Create a CakePHP command to increment the version for you
  4. Call the command when you push the new code to GitHub (Other version control systems are available)


Now whenever you update your application’s version number the resource files won’t be loaded from cache!

What did you think of today’s tutorial? Have questions on the implementation, think you could do it better? Let me know in the comments below!

If you like this tutorial consider subscribing for new tutorials every Tuesday, and a bonus post every Thursday.

Hope you’re staying warm out there!