PHPackages                             iqbalmalik89/guzzle-application-cache-subscriber - 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. [Caching](/categories/caching)
4. /
5. iqbalmalik89/guzzle-application-cache-subscriber

ActiveLibrary[Caching](/categories/caching)

iqbalmalik89/guzzle-application-cache-subscriber
================================================

Guzzle Plugin resp. Guzzle Subscriber to selectively cache a request/response on application level.

0.7.5(10y ago)09MITPHPPHP &gt;=5.5

Since Nov 13Pushed 6y agoCompare

[ Source](https://github.com/iqbalmalik89/guzzle-application-cache-subscriber)[ Packagist](https://packagist.org/packages/iqbalmalik89/guzzle-application-cache-subscriber)[ RSS](/packages/iqbalmalik89-guzzle-application-cache-subscriber/feed)WikiDiscussions master Synced today

READMEChangelogDependencies (3)Versions (10)Used By (0)

DEPRECATED ⛔
============

[](#deprecated-)

This repository has been deprecated as of 2019-01-27. That code was written a long time ago and has been unmaintained for several years. Thus, repository will now be [archived](https://github.blog/2017-11-08-archiving-repositories/). If you are interested in taking over ownership, feel free to [contact me](https://www.pascallandau.com/about/).

---

guzzle-application-cache-subscriber
===================================

[](#guzzle-application-cache-subscriber)

[![Build Status](https://camo.githubusercontent.com/915854fac9aef141753711ca4453f8987658f3ca365c10e19c4b7fc07a12c179/68747470733a2f2f7472617669732d63692e6f72672f7061736c616e6461752f67757a7a6c652d6170706c69636174696f6e2d63616368652d737562736372696265722e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/paslandau/guzzle-application-cache-subscriber)

Plugin for [Guzzle 5](https://github.com/scripts/guzzle) to cache requests/responses on an application level scope. This is different from the [CacheSubscriber](https://github.com/guzzle/cache-subscriber) because it doesn't adhere to HTTP caching standards but leaves it to the developer to decide what to cache and when to request a fresh response. Although I shamelessly used the [CacheStorage](https://github.com/guzzle/cache-subscriber/blob/0.1.0/src/CacheStorage.php) from said plugin :)

Description
-----------

[](#description)

This plugin works as a transparent proxy for requests made to the same URL using the same HTTP verb. I use it frequently when developing API wrappers to avoid making multiple calls to the same API endpoint. This is particularly helpful in cases where the API usage is restricted to a certain amount of requests.

The underlying cache library is [Doctrine/Cache](https://github.com/doctrine/cache) and I like to use the [FilesystemCache](https://github.com/doctrine/cache/blob/v1.3.1/lib/Doctrine/Common/Cache/FilesystemCache.php) to store responses on disk and have it available on the next test run.

### Basic Usage

[](#basic-usage)

```
$cache = new CacheStorage(new ArrayCache());
$sub = new ApplicationCacheSubscriber($cache);
$client = new Client();
$client->getEmitter()->attach($sub);

$num = 5;
$url = "http://www.example.com/";
for ($i = 1; $i get($url, ["debug" => true]);
    echo "Status code of $i. request: ".$resp->getStatusCode()."\n";
}
```

**Output**

```
Making 1. request:
* Hostname was NOT found in DNS cache
*   Trying 93.184.216.119...
* Connected to www.example.com (93.184.216.119) port 80 (#0)
> GET / HTTP/1.1
Host: www.example.com
User-Agent: Guzzle/5.0.3 curl/7.36.0 PHP/5.5.11

< HTTP/1.1 200 OK
< Accept-Ranges: bytes
< Cache-Control: max-age=604800
< Content-Type: text/html
< Date: Thu, 13 Nov 2014 09:54:15 GMT
< Etag: "359670651"
< Expires: Thu, 20 Nov 2014 09:54:15 GMT
< Last-Modified: Fri, 09 Aug 2013 23:54:35 GMT
* Server ECS (iad/182A) is not blacklisted
< Server: ECS (iad/182A)
< X-Cache: HIT
< x-ec-custom-error: 1
< Content-Length: 1270
<
* Connection #0 to host www.example.com left intact
Status code of 1. request: 200
Making 2. request:
Status code of 2. request: 200
Making 3. request:
Status code of 3. request: 200
Making 4. request:
Status code of 4. request: 200
Making 5. request:
Status code of 5. request: 200

```

Notice how only the first request produced a debug outbut. The remaining requests have been fetched from the cache and were intercepted in the `before` event.

### Examples

[](#examples)

See `examples` folder.

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

[](#requirements)

- PHP &gt;= 5.5
- Guzzle &gt;= 5.3.0
- Doctrine/Cache &gt;= 1.3.1

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

[](#installation)

The recommended way to install guzzle-application-cache-subscriber is through [Composer](http://getcomposer.org/).

```
curl -sS https://getcomposer.org/installer | php

```

Next, update your project's composer.json file to include GuzzleApplicationCacheSubscriber:

```
{
    "repositories": [ { "type": "composer", "url": "http://packages.myseosolution.de/"} ],
    "minimum-stability": "dev",
    "require": {
         "paslandau/guzzle-application-cache-subscriber": "dev-master"
    }
    "config": {
        "secure-http": false
    }
}

```

***Caution:** You need to explicitly set `"secure-http": false` in order to access  as repository. This change is required because composer changed the default setting for `secure-http` to true at [the end of february 2016](https://github.com/composer/composer/commit/cb59cf0c85e5b4a4a4d5c6e00f827ac830b54c70#diff-c26d84d5bc3eed1fec6a015a8fc0e0a7L55).*

After installing, you need to require Composer's autoloader:

```
require 'vendor/autoload.php';
```

General workflow and customization options
------------------------------------------

[](#general-workflow-and-customization-options)

The guzzle-application-cache-subscriber uses a closures (`canCacheRequest`) that is evaluated in the `end` event to decide wether a request/response can be stored in the cache. If it returns `true` and the response is not `null`, it is stored in the cache.

On a subsequent call to the same URL using the same HTTP verb, another closure (`mustRequestFresh`) is used in the `before` event to determine if the request can be answered from cache or not. If it returns `true` and the corresponding response has been cached before, the configuration key `has_cached_response` (`ApplicationCacheSubscriber::CACHED_RESPONSE_KEY`) is set to `true` so that this info might be evaluated later on. On `false`, the cached response is deleted and Guzzle proceeds to perform the request as usual.

### Setting up the validation closures

[](#setting-up-the-validation-closures)

```
$cache = new CacheStorage(new ArrayCache());

/**
 * Just some functions / closures for convenience
 */

$getConfigKeyValue = function (AbstractRequestEvent $e, $configKey){
    $request = $e->getRequest();
    return $request->getConfig()->get($configKey);
};

$setConfigKeyValue = function (AbstractRequestEvent $e, $configKey){
    $request = $e->getRequest();
    return $request->getConfig()->set($configKey, true);
};

/**
 * Setup the closures
 */

$mustRequestFreshKey = "requestFresh";
$mustRequestFresh = function(BeforeEvent $event) use ($mustRequestFreshKey, $getConfigKeyValue){
    $val = $getConfigKeyValue($event,$mustRequestFreshKey);
    if($val === null){
        return false;
    }
    if($val){
        echo "Making a fresh request.\n";
        return true;
    }else{
        echo "Trying to serve the response from cache.\n";
        return false;
    }
};

$canCacheRequestKey = "canCacheRequest";
$canCacheRequest = function(EndEvent $event) use ($canCacheRequestKey, $getConfigKeyValue){
    $val = $getConfigKeyValue($event,$canCacheRequestKey);
    if($val === null){
        return true;
    }
    if($val){
        echo "Caching the request/response.\n";
        return true;
    }else{
        echo "Not allowed to cache the request/response.\n";
        return false;
    }
};

$sub = new ApplicationCacheSubscriber($cache, $canCacheRequest, $mustRequestFresh);
$client = new Client();
$client->getEmitter()->attach($sub);

$url = "http://www.example.com/";
$requests = [];

//First request, caching is allowed
$r = $client->createRequest("GET",$url);
$r->getConfig()->add($canCacheRequestKey,true);
$requests[] = $r;
//Second request, get from cache
$r = $client->createRequest("GET",$url);
$r->getConfig()->add($mustRequestFreshKey,false);
$requests[] = $r;
//Third request, force fresh and disallow caching
$r = $client->createRequest("GET",$url);
$r->getConfig()->add($mustRequestFreshKey,true);
$r->getConfig()->add($canCacheRequestKey,false);
$requests[] = $r;
//Fourth request, try to serve from cache and allow caching
$r = $client->createRequest("GET",$url);
$r->getConfig()->add($mustRequestFreshKey,false);
$requests[] = $r;
//Fifth request, get it again from cache
$r = $client->createRequest("GET",$url);
$r->getConfig()->add($mustRequestFreshKey,false);
$requests[] = $r;

foreach ($requests as $i => $request) {
    echo "Request $i\n";
    $resp = $client->send($request);
    if($request->getConfig()->get(ApplicationCacheSubscriber::CACHED_RESPONSE_KEY)) {
        echo "The response came from cache\n\n";
    }else{
        echo "The response came not from cache\n\n";
    }
}
```

**Output**

```
Request 0
Caching the request/response.
The response came not from cache

Request 1
Trying to serve the response from cache.
The response came from cache

Request 2
Making a fresh request.
Not allowed to cache the request/response.
The response came not from cache

Request 3
Trying to serve the response from cache.
The response came not from cache

Request 4
Trying to serve the response from cache.
The response came from cache

```

Similar plugins
---------------

[](#similar-plugins)

- [CacheSubscriber (Guzzle 4 &amp; 5)](https://github.com/guzzle/cache-subscriber)
- [CachePlugin (Guzzle 3)](https://github.com/guzzle/plugin-cache/)

Frequently searched questions
-----------------------------

[](#frequently-searched-questions)

- How can I cache Guzzle requests/responses?

###  Health Score

24

—

LowBetter than 32% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity4

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 80% 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 ~48 days

Recently: every ~93 days

Total

9

Last Release

3808d ago

PHP version history (3 changes)0.0.1PHP ~5.5

0.2.0PHP ~5.5|~7

0.7.5PHP &gt;=5.5

### Community

Maintainers

![](https://www.gravatar.com/avatar/ae6c6c25f14ff8bdd961e2f8be318fb15e7125bf2f6ae28639853dc9010267f9?d=identicon)[iqbalmalik89](/maintainers/iqbalmalik89)

---

Top Contributors

[![paslandau](https://avatars.githubusercontent.com/u/7747310?v=4)](https://github.com/paslandau "paslandau (16 commits)")[![iqbalmalik89](https://avatars.githubusercontent.com/u/4177656?v=4)](https://github.com/iqbalmalik89 "iqbalmalik89 (4 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/iqbalmalik89-guzzle-application-cache-subscriber/health.svg)

```
[![Health](https://phpackages.com/badges/iqbalmalik89-guzzle-application-cache-subscriber/health.svg)](https://phpackages.com/packages/iqbalmalik89-guzzle-application-cache-subscriber)
```

###  Alternatives

[svix/svix

Svix PHP Library

3.2k722.4k6](/packages/svix-svix)[roave/doctrine-simplecache

Doctrine Cache adapter for PSR-16 Simple Cache

551.3M1](/packages/roave-doctrine-simplecache)[eliashaeussler/cache-warmup

Composer package to warm up website caches, based on a given XML sitemap

73387.5k5](/packages/eliashaeussler-cache-warmup)[eliashaeussler/typo3-warming

Warming - Warms up Frontend caches based on an XML sitemap. Cache warmup can be triggered via TYPO3 backend or using a console command. Supports multiple languages and custom crawler implementations.

20229.9k](/packages/eliashaeussler-typo3-warming)[biigle/laravel-file-cache

Fetch and cache files from local filesystem, cloud storage or public webservers in Laravel

1130.9k1](/packages/biigle-laravel-file-cache)

PHPackages © 2026

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