PHPackages                             gautammkgarg/psr-for-wordpress - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. gautammkgarg/psr-for-wordpress

ActiveLibrary[HTTP &amp; Networking](/categories/http)

gautammkgarg/psr-for-wordpress
==============================

PSR implementations for WordPress that bridge PSR interfaces to native WordPress APIs. PSR-18 HTTP Client (wp\_remote\_request) and PSR-16 Simple Cache (transients / wp\_cache) with companion key pattern.

v0.3(1w ago)215↓50%GPL-3.0-or-laterPHPPHP &gt;=8.1

Since Apr 15Pushed 1w agoCompare

[ Source](https://github.com/GautamMKGarg/psr-for-wordpress)[ Packagist](https://packagist.org/packages/gautammkgarg/psr-for-wordpress)[ RSS](/packages/gautammkgarg-psr-for-wordpress/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (2)Dependencies (11)Versions (4)Used By (0)

PSR for WordPress
=================

[](#psr-for-wordpress)

[![License: GPL v3](https://camo.githubusercontent.com/48bf9b56d44f38db53ce21294cf0b9487d0a3734ab3ba1fe4c69858ae20db2c1/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d47504c76332d626c75652e737667)](https://www.gnu.org/licenses/gpl-3.0)

A PSR implementation library for WordPress that bridges PSR interfaces to WordPress's native APIs. Currently implements:

- **PSR-18** HTTP Client — uses `wp_remote_request()` with fallback to `WpOrg\Requests`
- **PSR-16** Simple Cache — uses `set_transient()` / `wp_cache_set()` with the companion key pattern

---

Why This Package Exists
-----------------------

[](#why-this-package-exists)

WordPress bundles its own HTTP transport (`wp_remote_request`). It handles proxies, SSL, redirects, and other platform-specific concerns automatically.

Libraries like `omnipay/common`, and others use `php-http/discovery` to auto-detect a PSR-18 HTTP client. Without this package, they'd pull in Guzzle — adding a heavy dependency and bypassing WordPress's HTTP layer.

This package gives you:

- WordPress HTTP API as the transport inside WordPress
- `WpOrg\Requests` as fallback outside WordPress
- Zero-argument constructor for `php-http/discovery` auto-detection
- **PSR-18 compliance** — HTTP Client wherever `ClientInterface` is expected
- **PSR-16 compliance** — Simple Cache wherever `CacheInterface` is expected

---

Requirements
------------

[](#requirements)

- PHP 8.1+
- `rmccue/requests: ^2.0`
- WordPress 5.0+ when used inside WordPress

---

Installation
------------

[](#installation)

```
composer require gautammkgarg/psr-for-wordpress
```

---

Usage
-----

[](#usage)

### Auto-discovery (Omnipay, php-http/discovery)

[](#auto-discovery-omnipay-php-httpdiscovery)

Add to your project's `composer.json`:

```
{
    "extra": {
        "discovery": {
            "psr/http-client-implementation": "GautamMKGarg\\PsrForWordPress\\Http\\Psr18Client"
        }
    }
}
```

That's it. `php-http/discovery` will find `Psr18Client` automatically when any library calls `Psr18ClientDiscovery::find()`.

### Manual Usage

[](#manual-usage)

```
use GautamMKGarg\PsrForWordPress\Http\Psr18Client;
use Nyholm\Psr7\Factory\Psr17Factory;

$client = new Psr18Client();
$factory = new Psr17Factory();

$request = $factory->createRequest('GET', 'https://api.example.com/endpoint');
$response = $client->sendRequest($request);

echo $response->getStatusCode();    // 200
echo (string) $response->getBody(); // JSON response body
```

### Custom Options

[](#custom-options)

```
$client = new Psr18Client([
    'timeout'     => 30,   // seconds (default: 10)
    'redirection' => 0,    // disable redirects
    'sslverify'   => false, // disable SSL verification (not recommended in production)
]);
```

### Global Timeout Override via WordPress Filter

[](#global-timeout-override-via-wordpress-filter)

Instead of manually configuring the client, use WordPress's native hook:

```
add_filter('http_request_args', function(array $args, string $url): array {
    // Increase timeout for payment gateway API calls
    $args['timeout'] = 30;
    return $args;
}, 10, 2);
```

---

How It Works
------------

[](#how-it-works)

### Inside WordPress

[](#inside-wordpress)

When `wp_remote_request()` is available, the client calls it directly:

```
PSR-7 Request → Build WP args → wp_remote_request() → Parse WP response → PSR-7 Response
                                        ↓ on WP_Error
                               throw NetworkException

```

### Outside WordPress

[](#outside-wordpress)

Install dependency using `composer require rmccue/requests`.

When `wp_remote_request()` is not available:

```
PSR-7 Request → Build Requests options → WpOrg\Requests\Requests::request() → Parse response → PSR-7 Response
                                                    ↓ on exception
                                          throw NetworkException

```

---

Exceptions
----------

[](#exceptions)

ExceptionInterfaceWhen Thrown`NetworkException``Psr\Http\Client\NetworkExceptionInterface``WP_Error` or transport exception`RequestException``Psr\Http\Client\RequestExceptionInterface`Invalid request (e.g., empty URI)Both exceptions implement `getRequest()` to retrieve the original PSR-7 request.

PSR-16 Simple Cache
-------------------

[](#psr-16-simple-cache)

Two adapters are provided, both implementing `Psr\SimpleCache\CacheInterface`:

AdapterWordPress BackendPersistenceBest For`WpTransientsCache``set_transient`, `get_transient`Always persistent (DB by default, Redis if plugin)Tokens, API responses, settings that must survive requests`WpObjectCache``wp_cache_set`, `wp_cache_get`Only with Redis/Memcached pluginQuery results, computed values reused within request### Usage

[](#usage-1)

```
use GautamMKGarg\PsrForWordPress\Cache\WpTransientsCache;
use GautamMKGarg\PsrForWordPress\Cache\WpObjectCache;

// Persistent cache (survives requests)
$cache = new WpTransientsCache();

// In-memory cache (request-only unless Redis plugin)
$cache = new WpObjectCache('myplugin');

$cache->set('users', $users, 3600); // seconds
$users = $cache->get('users');
$cache->delete('users');
```

### Companion Key Pattern — Storing `false` Correctly

[](#companion-key-pattern--storing-false-correctly)

WordPress returns `false` for both "key not found" and "value is false". We solve this by creating a companion key (`{key}__found_psr16__`) only when `false` is stored. Non-false values are stored raw — so native `get_transient()` can read them without mangling.

FeatureThis PackageFalse handlingCompanion key (only for `false`)Native WordPress interop for non-false values✅ Yes — values stored rawPerformance overheadNear-zero (companion keys created only for `false` values)---

Guzzle vs This Package — Timeout Difference
-------------------------------------------

[](#guzzle-vs-this-package--timeout-difference)

Guzzle uses `0` as the default timeout, meaning **no timeout at all**. That's why Guzzle never fails for slow APIs. This package defaults to **10 seconds** — which is more appropriate for production WordPress sites than WordPress's built-in 5-second default. Increase it as needed.

---

License
-------

[](#license)

GPL-3.0-or-later. See [LICENSE](LICENSE) for full text.

###  Health Score

39

—

LowBetter than 84% of packages

Maintenance98

Actively maintained with recent releases

Popularity11

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity34

Early-stage or recently created project

 Bus Factor1

Top contributor holds 90% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~22 days

Total

3

Last Release

10d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/2cb8ae7a20d5829104baaa06822927affd88580b79ba277f043352114d9f7f0a?d=identicon)[GautamMKGarg](/maintainers/GautamMKGarg)

---

Top Contributors

[![knit-pay](https://avatars.githubusercontent.com/u/65900807?v=4)](https://github.com/knit-pay "knit-pay (9 commits)")[![GautamMKGarg](https://avatars.githubusercontent.com/u/15012617?v=4)](https://github.com/GautamMKGarg "GautamMKGarg (1 commits)")

---

Tags

httppsrwordpresshttp clientpsr-18cachesimple-cachepsr-16wprequeststransientsobject-cache

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/gautammkgarg-psr-for-wordpress/health.svg)

```
[![Health](https://phpackages.com/badges/gautammkgarg-psr-for-wordpress/health.svg)](https://phpackages.com/packages/gautammkgarg-psr-for-wordpress)
```

###  Alternatives

[guzzlehttp/psr7

PSR-7 message implementation that also provides common utility methods

7.9k1.1B3.7k](/packages/guzzlehttp-psr7)[cakephp/cakephp

The CakePHP framework

8.8k19.1M1.7k](/packages/cakephp-cakephp)[art4/requests-psr18-adapter

Use WordPress/Requests as a PSR-18 HTTP client

155.7k](/packages/art4-requests-psr18-adapter)[tempest/framework

The PHP framework that gets out of your way.

2.2k31.1k11](/packages/tempest-framework)[laudis/neo4j-php-client

Neo4j-PHP-Client is the most advanced PHP Client for Neo4j

185671.3k41](/packages/laudis-neo4j-php-client)[moonshine/moonshine

Laravel administration panel

1.3k239.9k72](/packages/moonshine-moonshine)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
