Automatically track who makes Database changes

19 September, 2007

Show comments

You may well find that you want to automatically know which user is adding or updating your database info. There are a few ways to do this and I recently, inadvertently, let slip that I have a whoDunnit (who did it) behavior which I use for exactly this purpose.

I wasn't sure if I should make it public; trouble is a little knowledge is a dangerous thing, and the technique used here could be (ab)used to bypass some of the structure and features that Cake brings to the developing-a-php-application table.

However, it is a very useful bit of code and for the benefit of anyone interested, the code is below:

This version does one thing and one thing only: It populates the user_id field with the current logged in user's ID for any save. It can be bypassed, which an administrative user might need to do to be able to allocate data with another user in the system, simply by calling $this->Model->enableWhodunnit(false); any time before saving. I do have another version in the works which will generate a basic audit trail style log (User X logged in, User X updated Y SUCCESS, User X deleted Z FAIL, User X logged out), but that, if you are interested, will have to wait for another day and preferably a bribe :).

Wrapping Up

A behavior, which records exactly what it says on the tin.

Bake on!