Using Guzzle in a WordPress plugin with PHP-Prefixer

Have you tried to use the fantastic ‘Guzzle’ on WordPress, but someone said it wasn’t a good idea due to the possible conflicts?

Guzzle is a PHP HTTP client built for PHP that makes it easy to send HTTPS requests. Interestingly, Guzzle offers a minimal API, making it possible for a developer to make HTTP or HTTPS requests to communicate with other applications efficiently. 

In short, Guzzle for WordPress is an excellent match, and now we learn how Guzzle can be prefixed and bundled as a WordPress plugin. 

Before understanding how to integrate Guzzle with PHP-Prefixer, let’s explore some benefits of using Guzzle for a developer.

Benefits of Guzzle

Let’s have a quick look over the benefits of Guzzle:

  • Send synchronous and asynchronous requests from the same interface. 
  • Abstracts away the underlying HTTP transport, allowing you to write code independent of the environment and transport.
  • There are no strict dependencies on cURL (a native library that will enable you to connect and communicate to many different servers), PHP streams, or non-blocking event loops.

Above all, it’s one of the excellent libraries for making HTTP calls using various methods.

To make your life easier, we provide a tutorial on installing the Guzzle and offer some brief examples to show you the power of this library! Let’s find out.

How are Guzzle and Composer helpful?

For importing third-party components into your PHP project, you rely heavily on PHP’s Composer dependency manager.  And, when it comes to WordPress, you should be careful when using Composer libraries, especially if you plan to share code with other WordPress users. If a WordPress site uses two plugins, i.e., plugin A and plugin B, with the same composer libraries but different versions, version v2.1, version v3.2, respectively, the chances of encountering a race condition becomes high.  As a result, you or your users will end up in Composer Dependency Hell.

Although WordPress has a deterministic method of loading plugins, and it is technically possible to manipulate them, this is pretty frustrating.  This is why you’ll have to take steps to isolate your code from the other plugins, which include potentially incompatible library versions.

A way to get around this is by employing a PHP Prefixing service that can wrap all Composer dependencies, and Guzzle is no exception. This HTTP library is perfect for WordPress because it can be prefixed and safely used in WordPress plugins. The prefixed Guzzle library will help you effectively deal with HTTP requests.

Prefixing Guzzle with PHP-Prefixer

PHP Prefixer wraps Composer libraries for your WordPress projects. It processes the dependencies to run along with other WordPress third-party plugins seamlessly. PHP-Prefixer schema definition declares your scope configuration, and this service packages the plugin and the associated libraries in a new unique space. 

PHP-Prefixer does not need a local installation. There are no Phars. There are no new dependencies. A PHP-Prefixer project can be up and running as quickly as possible. You are free to install any library, and PHP-Prefixer will manage your namespaces.

Since you know the what and why of PHP Prefixer, it’s time to look at how to use it to implement the Guzzle library on WordPress.

Sample project: Hello Guzzle

Let’s start with ‘Hello Prefixed World plugin’, a sample project based on the Hello Dolly plugin. The original Hello Dolly plugin comes pre-installed in WordPress, and it shows lyrics from the famous song in the WordPress admin. 

Some CSS is used in the PHP file to control how the lyrics are styled. This plugin has no practical use, you can delete it. It will not impact your WordPress site’s functionality, but why do you want to delete it, especially when you can make better use of it?

In a previous post, we presented how the ‘Hello Dolly’ plugin can be prefixed here: Using PHP Composer in the WordPress Ecosystem.

Essentially, this is how the modified Hello Dolly plugin looks after the prefixing process with the new PPP namespace:


// The modified version of the Hello Dolly plugin shows a formatted date before the lyrics
$now = \PPP\Carbon\Carbon::now();
$formattedDate = $now->toDateTimeString();

printf(
	'<p id="dolly"><span class="screen-reader-text">%s </span><span dir="ltr" %s="">%s // %s</span></p>',
	__( 'Quote from Hello Dolly song, by Jerry Herman:', 'hello-dolly' ),
	$lang,
	$formattedDate,
	$chosen
);

Now, we present a new case repurposing the Hello Dolly plugin to use the Guzzle library. In this sample project, we will integrate the Numbers API. This API is for interesting facts about numbers. It provides trivia, math, date, and year facts about numbers.

Just hit http://numbersapi.com/number/type to get a plain text response, where:

  • Type is one of trivia, math, date, or year. If omitted, trivia is used instead.
  • If the type is date & ranges of numbers, the number is an integer, or the keyword random, for which it will try to return a random available fact, or month/day (e.g., 1/19, 2/03, 06/10) if the type is date & ranges of numbers.

Let’s look at the example: http://numbersapi.com/273 trivia273 is the result given by Google and Bing for the query “273 is the zero of the Celsius temperature scale (to the nearest whole number) in Kelvin.

If you want to get facts about multiple numbers in one request, specify ranges for numbers in http://numbersapi.com/number/type. A number range (inclusive) is defined as minimum and maximum: multiple separate ranges and individual numbers (a comma). The response format will always be a JSON map from numbers to facts, of at most 100 numbers. 

Here is the example: http://numbersapi.com/6..8,10{ “6”: “6 is the number of basic holes or keys on most woodwind instruments.”, “7”: “7 is the number of colors of the rainbow.”, “8”: “8 is the number of bits in a byte.”, “10”: “10 is the number of years in a decade.” }

Combining the Numbers API and the “Hello Dolly”, we get a new plugin that renders number facts, and prefixing the Guzzle library with our PPP scope, the plugin is ready to be distributed:

use PPP\GuzzleHttp\Client as GuzzleHttpClient;
 
function hello_prefixed_guzzle_get_number_fact()
{
   // Create a client
   $client = new GuzzleHttpClient();
   $response = $client->get('http://numbersapi.com/'.mt_rand(0, 256));
 
   return wptexturize($response->getBody());
}
 
/ This just echoes the chosen line, we'll position it later.
function hello_prefixed_guzzle()
{
   require_once __DIR__.'/vendor/autoload.php';
 
   $randomNumberFact = hello_prefixed_guzzle_get_number_fact();
 
   $lang = '';
   if ('en_' !== substr(get_user_locale(), 0, 3)) {
       $lang = ' lang="en"';
   }
 
   // The modified version of the Hello Dolly plugin shows a number fact using Guzzle to query numbersapi.com.
   printf(
       '<p id="prefixed_guzzle"><span class="screen-reader-text">%s </span><span dir="ltr"%s>%s</span></p>',
       __('A random number fact from numbersapi.com:', 'hello-prefixed_guzzle'),
       $lang,
       $randomNumberFact

The plugin code is available in this repository:

https://github.com/PHP-Prefixer/using-guzzle-in-a-word-press-plugin-with-php-prefixer.

Finally, like the cherry on top, the repository includes the GitHub Action to run the prefixed job as a step of the development workflow.

Wrapping up

This article gave a sneak peek of Guzzle, which is now prefixed for WordPress, and the credit goes to PHP-Prefixer. PHP prefixer is a new & innovative way of designing solutions based on PHP libraries and Composer, and it has already set on a path to storm the web development galaxy (or at least our little corner). 

Apart from offering on-demand resources to process PHP Composer packages, PHP-Prefixer improves the time to market for your most prominent idea

PHP-Prefixer promises excellent prefixing results in WordPress plugins. Just declare what to prefix, and we will take care of the rest!

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.