PHP – Limit on Global Consts Before Bad Programming

code smellcode-qualityobject-orientedPHPprogramming practices

Basically, I develop websites, some large with many crud operations, etc…

However I've gotten into the habit of storing re-usable data as a constant in my PHP applications

I currently have 44 constants defined in one application.

These range from:

  • Database config
  • Home page for admin and guest
  • url slug names
  • declaring development mode
  • declaring maintenance mode
  • a few directory shortcuts ( instead of writing /admin/templates/images ill use const ADM_IMAGES )
  • session names
  • cookie names
  • random things like MAX_IMAGE_SIZE, THUMB_SIZE and MAX_LOGIN_ATTEMPTS

I don't have any problems using all these constants… It's kind of helpful having all these in my application.

I just wanted to know if its a 'good practise' to use them in this excess

If not, how else could this data be encapsulated to be useful AND easy enough to reach in my application? Also bearing readability in mind.

Best Answer

It's okay to break programming rules if you understand the potential problems the rules are designed to avoid. For global constants, the main problems are discoverability, name clashes, difficulty unit testing, and difficulty recognizing poor cohesion. I would seriously consider refactoring them out in the following circumstances:

  • You are constantly hunting around trying to find either where an existing constant is defined, or where a new one should be.
  • You find yourself making names like HOME1, HOME2, etc. because the name you wanted is already taken.
  • The example is causing a less experienced colleague to use globals where they are neither helpful nor more readable.
  • You are wanting write unit tests that need to change those constants.
  • Feature requests or bugs frequently require changing several files.

To take them out, you have a couple options:

  • Limit the scope of a constant to a single file instead of the entire application. If this is difficult to do, it probably means your code is not cohesive enough and needs refactoring.

  • Make an object or objects that you pass to functions that need it. This takes some practice to define a hierarchy that works.