DEV Community

Cover image for How To: Using Guzzle and prefixing a WordPress plugin
Anibal Sanchez for PHP-Prefixer

Posted on

How To: Using Guzzle and prefixing a WordPress plugin

This post was originally published on blog.php-prefixer.com. This tutorial is the second post in a series about WordPress plugin development based on PHP Prefixer. You can read the previous article here: Using PHP Composer in the WordPress Ecosystem.

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. 

How To: Using Guzzle and prefixing a WordPress

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 the previous post, we presented how the ‘*Hello Dolly*’ plugin can be prefixed here: Using PHP Composer in the WordPress Ecosystem.

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
Enter fullscreen mode Exit fullscreen mode

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.

Using the Command-Line and GitHub Actions

Assuming that you completed the previous tutorial in the series, you know how to create a project and prefix a build. You are ready to prefix PHP code using the Command-line and GitHub Actions to improve your development toolchain.

The PHP-Prefixer service has a command-line (CLI) that empowers you to use the service locally and process the project source code from your workstation.

The command calls the PHP-Prefixer service using the REST API to submit a project source code, apply the prefixes, wait and download the results.

The PHP-Prefixer CLI is available here: https://github.com/PHP-Prefixer/php-prefixer-cli.

Enter GitHub Actions for PHP-Prefixer

In software engineering, CI/CD or CICD is the combined practice of continuous integration and delivery or deployment. CI/CD bridges the gaps between development and operation activities by enforcing automation in the building, testing, and deployment of applications.

To facilitate the usage of PHP-Prefixer, the Command-Line provides an ideal tool to integrate the prefixing service in any CI/CD context. As a reference implementation, you can check the official PHP Prefixer Build Action.

To use the Action, you must create an account on PHP-Prefixer and prepare your projects with the prefix defined in the composer.json schema. You can first prefix your project on the service web interface and then integrate Action in your repositories. Before using the Action and the command-line, we recommend checking the documentation and guides here: https://php-prefixer.com/docs/guides/.

Create your Github Workflow configuration in .github/workflows/prefixer.yml.

name: Prefixer

on: [push]

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout
        uses: actions/checkout@v2

      - name: Run PHP-Prefixer
        uses: PHP-Prefixer/php-prefixer-build-action@v0.0.6
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          personal_access_token: ${{ secrets.PERSONAL_ACCESS_TOKEN }}
          project_id: ${{ secrets.PROJECT_ID }}
    # ... then your own project steps ...
Enter fullscreen mode Exit fullscreen mode

Running PHP Prefixer Build Action

The Action is a straightforward implementation of the PHP-Prefixer CLI. The Action clones the repository, packages the project in a ZIP file, sends the source code to PHP-Prefixer, and receives the results. The new package is then committed to the prefixed branch to make it available at the repository level.

The sample Action is configured on the sample plugin repository that you can run manually.

Step 1: Run the GitHub Action

Step 1: Run the GitHub Action

Step 2: Wait for the PHP-Prefixer process

Step 2: Wait for the PHP-Prefixer process

Step 3: The Action is completed, and the results are committed to the prefixed branch

Step 3: The Action is completed, and the results are committed to the prefixed branch

In this sample, we can see how the GitHub Action runs and processes the output that the user receives on the screen. It might take a few iterations to fix syntax and get everything right, but a successful prefixed project is an outcome. The results can be checked in the WordPress plugin prefixed branch: https://github.com/PHP-Prefixer/using-guzzle-in-a-word-press-plug-in-with-php-prefixer/tree/prefixed.

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!

Latest comments (0)