← All languages

Servirtium for

PHP

No shipped package: vendor the binding's source at a release tag, with the native library from the release. Release v2.0.0-alpha.20.

FFI mechanism
PHP FFI (FFI::cdef). The Composer package declares the C ABI of libservirtium_vcr with FFI::cdef and presents a fluent builder (Vcr::playback / Vcr::record ... ->start()). No Servirtium logic is reimplemented in PHP.
Toolchain
PHP 8.2+ with ext-ffi (composer.json: php >=8.2, ext-ffi) and Composer. Checked on PHP 8.5.13, Composer 2. (php/docs/building.md says 8.4+ for developing the binding itself.)
Distribution
Not on Packagist. Composer path repository onto a checkout of the tag, plus the release native library
Finding the library
Looks for php/native/libservirtium_vcr.so (or .dylib; servirtium_vcr.dll on Windows) inside the package. Overridden by SERVIRTIUM_VCR_LIB (absolute path) or ->nativeLib($path) on the builder, or Vcr::playback($tape, $libPath).
On GitHub
php/ · README

Getting it

There is no published package for PHP. You vendor the binding's source into your project at the release tag v2.0.0-alpha.20 and take the native library from the same release.

  1. There is no one-line composer require: composer.json lives in php/ of a monorepo, and Composer's vcs repository type only reads a repository root. Use a path repository onto a checkout of the tag. First clone the tag (only php/ is used).
    VER=v2.0.0-alpha.20
    git clone --depth 1 --branch $VER https://github.com/servirtium/servirtium-vcr.git vendor-src/servirtium-vcr
    
  2. Download the native library for your platform into that checkout's php/native/, verify its checksum, and give it the plain file name the loader wants.
    REL=https://github.com/servirtium/servirtium-vcr/releases/download/$VER
    # Linux x86_64 shown; macOS arm64 is macos-arm64 + .dylib; see the release assets for others
    LIB=libservirtium_vcr-$VER-linux-x86_64.so
    N=vendor-src/servirtium-vcr/php/native
    mkdir -p $N
    curl -fsSL -o $N/$LIB $REL/$LIB
    curl -fsSL -o $N/$LIB.sha256 $REL/$LIB.sha256
    ( cd $N && { sha256sum -c $LIB.sha256 || shasum -a 256 -c $LIB.sha256; } )
    cp $N/$LIB $N/libservirtium_vcr.so
    
  3. Register the path repository and require the package (name servirtium/vcr, namespace Servirtium\).
    composer config repositories.servirtium path vendor-src/servirtium-vcr/php
    composer require --dev servirtium/vcr:@dev
    
  4. Check it with a canned tape. The FFI extension must be enabled; on distros that ship it as a module php.ini does not load (Arch), add -d extension=ffi.
    mkdir -p tapes
    curl -fsSL -o tapes/single_get.md https://raw.githubusercontent.com/servirtium/servirtium-vcr/$VER/php/example/tapes/single_get.md
    php -d ffi.enable=1 -r 'require "vendor/autoload.php";
      $v = Servirtium\Vcr::playback("tapes/single_get.md")->port(0)->start();
      echo file_get_contents($v->baseUrl()."/ok"), "\n"; $v->stop();'   # -> ok-body
    

Record

Point your client at the VCR's base URL; the VCR forwards to the real service and hands back the real response. Nothing is written until you commit.

use Servirtium\Vcr;
use Servirtium\VcrOutcome;

$vcr = Vcr::record('tapes/climate_api.md', 'https://climatedataapi.worldbank.org')
    ->port(0)->start();
try {
    // point the SUT at $vcr->baseUrl() ...
    file_get_contents($vcr->baseUrl() . '/api/v1/countries');
    assert($vcr->lastKind() === VcrOutcome::Ok);
    $vcr->commit();            // writes the tape; stop() without commit()/discard() writes nothing and throws
} catch (\Throwable $e) {
    $vcr->discard();           // drop the recording, no tape written
    throw $e;
}

Playback

The same tape, replayed with no network.

use Servirtium\Vcr;
use Servirtium\VcrOutcome;

$vcr = Vcr::playback('tapes/climate_api.md')->port(0)->start();   // port 0 = OS-assigned
try {
    // point the SUT at $vcr->baseUrl(), drive it ...
    $body = file_get_contents($vcr->baseUrl() . '/api/v1/countries');
    assert($vcr->lastKind() === VcrOutcome::Ok);
    $vcr->assertAllConsumed();
} finally {
    $vcr->stop();
}

Idiomatic extras

Redact a secret at commit time

The live SUT still sees real bytes; only the written tape is scrubbed. VcrField is Path, ResponseBody, RequestHeaders, RequestBody or ResponseHeaders.

use Servirtium\VcrField;

Vcr::record($tape, $upstream)
    ->redactHeader('Authorization')                 // request header, replaced by [REDACTED]
    ->redactQueryParam('password')
    ->redact(VcrField::ResponseBody, 'Bearer abc123', 'Bearer REDACTED')
    ->redactCredentials()                           // Authorization, cookies, common key headers
    ->start();

Volatile value that round-trips

A {{placeholder}} rule makes a re-record byte-identical; on playback a recorded token matches any live value, and a response token must be bound with bind().

Vcr::playback($tape)
    ->volatileRule('response headers', 'Date: {{serverDate}}')
    ->bind('serverDate', gmdate('D, d M Y H:i:s') . ' GMT')
    ->start();

Strict headers and diagnostics

Opt-in header comparison; a mismatch answers 599 and fills lastError().

$vcr = Vcr::playback($tape)->strictHeaders()->start();
// ... drive the SUT ...
if ($vcr->lastKind() !== VcrOutcome::Ok) { throw new \RuntimeException($vcr->lastError()); }

Gotchas

  • ext-ffi is a hard requirement. In the CLI ffi.enable=preload (the php.ini default) still allows FFI::cdef; under php-fpm or Apache set ffi.enable=1.
  • Keep the native library out of vendor/: composer install can wipe it. Do not set options.symlink=false unless the library is already in php/native/.
  • Could not find a matching version of package servirtium/vcr means the path repository is not configured, or points at the repo root instead of its php/ subdirectory; a vcs repository cannot work.
  • A record that is stopped without commit() or discard() writes nothing and throws VcrException.
  • PHP HTTP clients add default request headers; under strictHeaders() record with the same client or drop them with removeHeader(VcrField::RequestHeaders, ...).

Prompt for your coding agent

Paste this into Claude, Codex, Gemini or any coding agent, in your PHP project. It wraps one of your existing integration tests with Servirtium. The general prompt has a slot for the language instead.

Hey Gemini or Claude or Codex,

I want a test in this PHP project to run without calling a real web service every time. Use Servirtium (https://servirtium.dev), which records HTTP conversations as readable Markdown "tapes" and replays them. Do these steps in order and tell me what you did at each one.

1. Find an existing integration test in this project that calls a web service as a side effect of what it is testing. Prefer one that is slow, flaky, or needs credentials or network because of that call. Tell me which test you chose and why.

2. Add the Servirtium binding for PHP. Follow https://servirtium.dev/languages/php/ exactly. Servirtium ships no package for this language. Vendor the binding's source into the project at the release tag v2.0.0-alpha.20 and put the native library from the same release where the page says: Not on Packagist. Composer path repository onto a checkout of the tag, plus the release native library.
   Toolchain and minimum version: PHP 8.2+ with ext-ffi (composer.json: php >=8.2, ext-ffi) and Composer. Checked on PHP 8.5.13, Composer 2. (php/docs/building.md says 8.4+ for developing the binding itself.).
   How the binding finds the native library: Looks for php/native/libservirtium_vcr.so (or .dylib; servirtium_vcr.dll on Windows) inside the package. Overridden by SERVIRTIUM_VCR_LIB (absolute path) or ->nativeLib($path) on the builder, or Vcr::playback($tape, $libPath).

3. Route that test's HTTP client to the Servirtium VCR's base URL instead of the real service, using the idiomatic PHP way of setting a base URL or HTTP client. The VCR starts on its own port (use port 0, so it picks a free one) and gives you its base URL; give that URL to the client and never hard-code a port.

4. Run the test once in record mode against the real service. Commit the recording when the test passes and discard it when the test fails: a record VCR that is closed without a commit or a discard writes no tape and raises an error. Use redact_credentials (the spelling for PHP is on the page) so secrets become numbered tokens, and remove volatile request headers such as User-Agent and Date from the tape so playback does not depend on them.

5. Keep the tape beside the test as readable Markdown, in version control. Open it and check there are no secrets or personal data in it before committing.

6. Make the test play back by default, with an explicit switch (for example an environment variable such as SERVIRTIUM_RECORD=1) that re-records.

7. Prove it works offline: make the real service unreachable (network off, or a wrong host) and show the test still passes in playback.

Traps to avoid:
- A record VCR needs Commit() or Discard(); closing it without either writes nothing and raises.
- The VCR runs in your test process on its own port; the system under test must use the VCR's base URL, not the real one.
- ext-ffi is a hard requirement. In the CLI ffi.enable=preload (the php.ini default) still allows FFI::cdef; under php-fpm or Apache set ffi.enable=1.
- Keep the native library out of vendor/: composer install can wipe it. Do not set options.symlink=false unless the library is already in php/native/.
- Could not find a matching version of package servirtium/vcr means the path repository is not configured, or points at the repo root instead of its php/ subdirectory; a vcs repository cannot work.
- A record that is stopped without commit() or discard() writes nothing and throws VcrException.
- PHP HTTP clients add default request headers; under strictHeaders() record with the same client or drop them with removeHeader(VcrField::RequestHeaders, ...).

References:
- This language's page: https://servirtium.dev/languages/php/
- The binding's directory: https://github.com/servirtium/servirtium-vcr/tree/main/php
- Concepts, features and every language's quick start: https://servirtium.dev/llms-full.txt (index: https://servirtium.dev/llms.txt)

How these snippets were checked

On cachyos (linux-x86_64, PHP 8.5.13, Composer 2): followed the Getting it steps verbatim (release tag clone, release .so with sha256 check, composer path repo + require --dev servirtium/vcr:@dev, -d extension=ffi because Arch does not load FFI by default) and the check one-liner printed ok-body. Also ran the record snippet (with a redact() rule) against a local upstream: commit() wrote the tape, it replayed with VcrOutcome::Ok and assertAllConsumed(); stop() without commit() threw and wrote no file; volatileRule()+bind() accepted on playback. strictHeaders extra and redactHeader/redactQueryParam/redactCredentials names checked against src/RecordBuilder.php only, not run.

They mirror these files in the repository:

See also the feature reference, llms.txt and the php/ directory.