TL;DR: Here’s an easy way to incorporate Ray into all of your WordPress projects without needing to add use at the top of your project files. Thanks to my friend Aubrey for sharing this.


You know about Ray, right? I’ve talked about it twice already:

  1. Debugging WordPress with Ray, Part 1
  2. Debugging WordPress with Ray, Part 2

If you’ve been using Ray in your WordPress projects and have been including it in your composer.json file, then you’ve likely set up the top of your files like this:

use WP_Post;
use WP_Term;
use Spatie\Ray;

defined('WPINC') || die;
require_once __DIR__ . '/vendor/autoload.php';

Notice that the namespace for Ray is included in this. But if this is a utility meant for printing out error messages for debugging purposes, much like we’re used to seeing with Xdebug, then why would we include it in every file? That is, why would we include a use statement for a dependency that’s not sent to production?

We don’t have to do so.

Ray Per Project at an Application Level

This post was inspired by the following tweet:

When it comes to running Composer and Ray in conjunction with one another and when it comes to doing so at a project level (usually at the level of a plugin), I find that I like to keep the Ray package installed in the project’s required-dev dependencies.

This keeps it from needing to be bundled with anything that goes to production; however, I don’t need to include use Spatie\Ray whenever I’m deploying a project to production, either.

So what’s a good middle ground?

First, add the following to composer.json in your project’s directory:

"require-dev": {
    ...,
    "spatie/ray": "^1.29.0"
},

Next, in your WordPress installation’s wp-config.php file, add the following line just under the first block of comments:

use Spatie\Ray;

This will ensure that Ray is installed at a per-project level and only for development purposes, but will also be declared at an application configuration level such that your plugins don’t need to incorporate them into their files for you to take advantage of the ray() function.


📝 Note: Out of the box, the ray function is designed to work without needing to reference any namespaces; however, if you’re looking to incorporate its main class or any of the classes in the library, then use comes in handy so not to have to share the fully-qualified name of the library. An example.