...

Use Custom Functions to Determine Which Environment You’re Running Your Code

Use Custom Functions to Determine Which Environment You’re Running Your Code

You might also like

WordPress provides constants and functions for setting up and checking to see if we’re in development mode.

Specifically, see the following:

But if you’re in a situation in which you’re working on code that’s, say, WordPress-adjacent where it both talks to third-party APIs and services but also sends data to WordPress (or reads data from WordPress), it may be helpful to have another way to determine if your code is running on a local machine.

Use Custom Functions

Case in Point

Perhaps you’re going to be registering a JavaScript file that requires a dependencies that is not available on your local machine. If this is the case, you have a few options:

  1. Find all of the dependencies from the production application and add them to your local machine ignoring whatever side effects may happen,
  2. Remove a call to the dependencies in your code and try to remember to add it back before committing to source code,
  3. Or use a a drop-in function for checking if you’re running the code locally.

Though I know each option has its own tradeoffs, I find myself doing the third option more often than not. All it requires is evaluating the loopback interface and seeing where the script is running.

In the context of PHP, a loopback interface refers to the ability of a script or a server to send requests to itself. So if you check to see if it’s running on 127.0.0.1, which is an IPv4 variation of localhost or ::1 which is the IPv6 variation of localhost then you can determine how to move foward.

A Simple Example

Here’s my example function:

public function isLocalDevelopmentEnvironment()
{ return ( 0 === strcasecmp('::1', $_SERVER['REMOTE_ADDR']) || 0 === strcasecmp('127.0.0.1', $_SERVER['REMOTE_ADDR']) );
}

Then if you want to use this when, say, enqueuing JavaScript sources in WordPress, you can set up a conditional for dependencies like this:

$dependencies = ['jquery', 'acme-scripts'];
if ($this->isLocalDevelopmentEnvironment()) { $dependencies = ['jquery'];
}

Then you can enqueue the scripts like this:

wp_enqueue_script( 'acme', $this->jsDir . 'omega.js', $dependencies, filemtime(__FILE__), true
);

Sure, it’s a simple example but there’s much more that can be done with that single helper function regardless of if you’re working with WordPress, Google Cloud Functions, cloud databases, or more.

There are, of course, much more complicated ways in which custom functions can be written and used. The point isn’t about complexity, though. It’s about thinking through when utility functions like this are helpful and when they should be used.

Being a Software Developer | Tom McFarlin

Being a Software Developer

Not everyone who works in software development has a degree in computer science (or a degree at all), and I’m…