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:
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:
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:
Use @spatie_be Ray? Tired of having to hunt in debug.log for errors/warnings and wish they would just show up in Ray?https://t.co/GUR7LOuAgm Add this to your wp-config.php(make sure you computer require it in WordPress root and require autoload.php in vendor/)— Aubrey (@aubreypwd) December 27, 2021
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 SpatieRay 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:
Next, in your WordPress installation’s wp-config.php file, add the following line just under the first block of comments:
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.