PHPackages                             icecave/isolator - 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. [Testing &amp; Quality](/categories/testing)
4. /
5. icecave/isolator

ActiveLibrary[Testing &amp; Quality](/categories/testing)

icecave/isolator
================

Dependency injection for global functions.

3.0.3(11y ago)351.4M↓21.3%4[1 issues](https://github.com/icecave/isolator/issues)20MITPHPPHP &gt;=5.3CI failing

Since Jul 10Pushed 7y ago5 watchersCompare

[ Source](https://github.com/icecave/isolator)[ Packagist](https://packagist.org/packages/icecave/isolator)[ Docs](https://github.com/IcecaveStudios/isolator)[ RSS](/packages/icecave-isolator/feed)WikiDiscussions master Synced 3d ago

READMEChangelog (10)Dependencies (1)Versions (14)Used By (20)

Isolator
========

[](#isolator)

[![Build Status](https://camo.githubusercontent.com/737750a6daabbae225c90dcedaf1bde68b82a4e9cf1cd2ef7628e51d28849433/687474703a2f2f696d672e736869656c64732e696f2f7472617669732f696365636176652f69736f6c61746f722f6d61737465722e7376673f7374796c653d666c61742d737175617265)](https://travis-ci.org/icecave/isolator)[![Code Coverage](https://camo.githubusercontent.com/e54df7140d02476d06f1ccf31a34b480fac9bb5bd3ec59ecf9a1dc5917b85288/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f696365636176652f69736f6c61746f722f6d61737465722e7376673f7374796c653d666c61742d737175617265)](https://codecov.io/github/icecave/isolator)[![Latest Version](https://camo.githubusercontent.com/fb58e0ab80854288132a281791818490de91f2bb01d16358a2b7948fb8288ce0/687474703a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f696365636176652f69736f6c61746f722e7376673f7374796c653d666c61742d737175617265266c6162656c3d73656d766572)](https://semver.org)

**Isolator** simplifies testing of classes that make use of global functions by treating all global functions as methods on an "isolator" object.

```
composer require icecave/isolator

```

Rationale
---------

[](#rationale)

A large number of PHP extensions (and the PHP core) implement their functionality as global functions. Testing classes that use these functions quickly becomes difficult due to the inability to replace them with [test doubles](http://en.wikipedia.org/wiki/Test_double).

**Isolator** endeavours to solve this problem by acting as a proxy between your class and global functions. An isolator instance is passed into your object as a [dependency](http://en.wikipedia.org/wiki/Dependency_injection) and used in place of any global function calls that you may want to replace when testing.

Example
-------

[](#example)

The following class makes use of [file\_get\_contents()](http://php.net/manual/en/function.file-get-contents.php) to read the contents of a file.

```
class MyDocument
{
    public function __construct($filename)
    {
        $this->filename = $filename;
    }

    public function getContents()
    {
        return file_get_contents($this->filename);
    }

    protected $filename;
}
```

Despite the simplicity of the example, the class immediately becomes difficult to test due to it's reliance on the filesystem. In order to test this class you might be inclined to set up some static fixtures on disk, make a temporary directory when your test suite is set up or perhaps even use a [virtual filesystem wrapper](http://code.google.com/p/bovigo/wiki/vfsStream).

**Isolator** provides a fourth alternative. Given below is the same example rewritten using an `Isolator` instance.

```
use Icecave\Isolator\Isolator;

class MyDocument
{
    public function __construct($filename, Isolator $isolator = null)
    {
        $this->filename = $filename;
        $this->isolator = Isolator::get($isolator);
    }

    public function getContents()
    {
        return $this->isolator->file_get_contents($this->filename);
    }

    protected $filename;
    protected $isolator;
}
```

`MyDocument` now takes an instance of `Isolator` in it's constructor. It would be a pain - and unnecessary - to create a new `Isolator` instance every time you construct an object in your production code, so a shared instance is made accessible using the `Isolator::get()` method. If a non-null value is passed to `Isolator::get()` it is returned unchanged, allowing you to replace the isolator when necessary.

`MyDocument::getContents()` is also updated to use the isolator instance rather than calling the global function directly. The behavior of `MyDocument` remains unchanged but testing the class is easy, as will be shown in the example test suite below.

*Note: The test below is written for the [PHPUnit](http://www.phpunit.de) testing framework, using [Phake](https://github.com/mlively/Phake)for mocking. Phake provides a more flexible alternative to PHPUnit's built-in mock objects.*

```
class MyDocumentTest extends PHPUnit\Framework\TestCase
{
    public function setUp()
    {
        // First a mocked isolator instance is created ...
        $this->isolator = Phake::mock('Icecave\Isolator\Isolator');

        // That isolator instance is given to the MyDocument instance
        // that is to be tested ...
        $this->myDocument = new MyDocument('foo.txt', $this->isolator);
    }

    public function testGetContents()
    {
        // Phake is used to configure the mocked isolator to return a known
        // string when file_get_contents() is called with a parameter equal
        // to 'foo.txt' ...
        Phake::when($this->isolator)
          ->file_get_contents('foo.txt')
          ->thenReturn('This is the file contents.');

        // MyDocument::getContents() is called, and it's result checked ...
        $contents = $this->myDocument->getContents();
        $this->assertEquals($contents, 'This is the file contents.');

        // Finally Phake is used to verify that a call to file_get_contents()
        // was made as expected ...
        Phake::verify($this->isolator)
          ->file_get_contents('foo.txt');
    }
}
```

The test verifies the behavior of the `MyDocument` class completely, without requiring any disk access.

Using an isolator is most helpful when testing code that uses functions which maintain global state or utilize external resources such as databases, filesystems, etc. It is usually unnecessary to mock out deterministic functions such as `strlen()`, for example.

Isolator Trait
--------------

[](#isolator-trait)

In PHP 5.4 and later, it is also possible to use `IsolatorTrait` to bring an isolator into your class. The isolator instance is accessed using `$this->isolator()` and can be set via `$this->setIsolator()`.

```
use Icecave\Isolator\IsolatorTrait;

class MyDocument
{
    use IsolatorTrait;

    public function __construct($filename)
    {
        $this->filename = $filename;
    }

    public function getContents()
    {
        return $this->isolator()->file_get_contents($this->filename);
    }

    protected $filename;
}
```

Language Constructs
-------------------

[](#language-constructs)

**Isolator** can also be used to invoke the following function-like language constructs:

- `include`, `include_once`, `require` and `require_once`
- `exit` and `die`
- `echo`
- `eval`
- `new`

Peculiarities
-------------

[](#peculiarities)

Several of PHP's core global functions have some peculiarities and inconsitencies in the way they are defined. **Isolator** attempts to accomodate such inconsistencies when possible, but may have issues with some native C functions for which parameter reflection information is non-standard or incorrect. These issues seem to be largely rectified as of PHP 5.6.

###  Health Score

42

—

FairBetter than 88% of packages

Maintenance19

Infrequent updates — may be unmaintained

Popularity48

Moderate usage in the ecosystem

Community25

Small or concentrated contributor base

Maturity65

Established project with proven stability

 Bus Factor1

Top contributor holds 98.3% 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 ~82 days

Recently: every ~56 days

Total

13

Last Release

4117d ago

Major Versions

1.0.1 → 2.0.02012-08-05

2.3.0 → 3.0.02014-10-08

PHP version history (3 changes)1.0.0PHP &gt;=5.3.0

2.1.2PHP &gt;=5.3.3

2.2.0PHP &gt;=5.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/93a71bd75fcd51efee464532dbdd54927cd00e938805998c76e0a804d38fa3fb?d=identicon)[jmalloc](/maintainers/jmalloc)

---

Top Contributors

[![jmalloc](https://avatars.githubusercontent.com/u/761536?v=4)](https://github.com/jmalloc "jmalloc (113 commits)")[![ezzatron](https://avatars.githubusercontent.com/u/100152?v=4)](https://github.com/ezzatron "ezzatron (2 commits)")

---

Tags

phpunitunittestmockstubfakeDouble

### Embed Badge

![Health badge](/badges/icecave-isolator/health.svg)

```
[![Health](https://phpackages.com/badges/icecave-isolator/health.svg)](https://phpackages.com/packages/icecave-isolator)
```

###  Alternatives

[phpspec/prophecy

Highly opinionated mocking framework for PHP 5.3+

8.5k560.2M782](/packages/phpspec-prophecy)[mockery/mockery

Mockery is a simple yet flexible PHP mock object framework

10.7k526.2M26.9k](/packages/mockery-mockery)[php-mock/php-mock-phpunit

Mock built-in PHP functions (e.g. time()) with PHPUnit. This package relies on PHP's namespace fallback policy. No further extension is needed.

1719.0M542](/packages/php-mock-php-mock-phpunit)[php-mock/php-mock

PHP-Mock can mock built-in PHP functions (e.g. time()). PHP-Mock relies on PHP's namespace fallback policy. No further extension is needed.

37419.9M125](/packages/php-mock-php-mock)[colinodell/psr-testlogger

PSR-3 compliant test logger based on psr/log v1's, but compatible with v2 and v3 too!

1813.8M77](/packages/colinodell-psr-testlogger)[elliotchance/concise

Concise is test framework for using plain English and minimal code, built on PHPUnit.

47224.2k4](/packages/elliotchance-concise)

PHPackages © 2026

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