CakePHP 2: Hard Coding Primary Keys into Logic or Queries

As a developer I know that it’s always often too easy to take shortcuts and in the back of your mind you may think “I really shouldn’t be doing this, but I can come back later and fix it up once I complete this feature!”. I know that I am guilty of this, and quite often sometimes forget to fix up that code until after production, due to the sheer amount of work required to finish the project.


One of the issues I have run into previously is wanting to use a particular primary key / foreign key in a conditional statement, but I don’t really want to query a second table first to get the correct primary key.

It becomes all too tempting to write the primary key manually in the interest of time, you know it’s unlikely to change right, so what’s the big deal? The problem occurs when you hard code this primary key in several methods or several files, then one day unexpectedly the value changes and the website needs updating – now you must trace each occurrence and update them manually and in a large project you may miss a few until a customer finds it first (which is bad).

But what about the alternative? You have to write a query to find the primary key and usually by name (which is also  subject to change, probably more likely subject to change than the id). Assuming your id changes you will have the new id each time, but you also have the added strain of another query (likely to be insignificant but still a factor) as well as the added time of writing said query.

Example Query

Here is my example query in which I am using a hard coded primary / foreign key.

What I recommend

If you can use a query and it’s guaranteed to work each time with little strain added, I would always recommend you do this above everything else, but for those of us who don’t know if the data will change or are more than likely going to hard code a integer into the query this may help you.

In your CakePHP bootstrap.php file, I always include a separate config file, you may name this anything you want for this example I will name it application.php. Include the file using by writing  require(APP . DS . 'Config' . DS . 'application.php'); .

In your application.php file you can do something like the following:

And now if we return to our example from earlier we can update it like such

And as you can see it’s a really simple concept, define a constant with the id as a configuration file, use it throughout the application where needed. If your admin primary key / foreign key ever changes you just update the config file and it will update the rest of the website.

I’d love to hear your views on this, as I said earlier I recommend using a query where ever possible, but for those times you find it too tempting to write the id manually – just use this method to save a headache down the line.

Leave a Reply

Your email address will not be published. Required fields are marked *