PHPackages                             axy/env - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. axy/env

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

axy/env
=======

Abstracting access to the environment

0.2.0(10y ago)013411MITPHPPHP &gt;=5.4.0

Since Nov 5Pushed 8y ago1 watchersCompare

[ Source](https://github.com/axypro/env)[ Packagist](https://packagist.org/packages/axy/env)[ Docs](https://github.com/axypro/env)[ RSS](/packages/axy-env/feed)WikiDiscussions master Synced today

READMEChangelogDependencies (1)Versions (6)Used By (1)

axy\\env
========

[](#axyenv)

Abstracting access to the environment (PHP).

[![Latest Stable Version](https://camo.githubusercontent.com/39b61546863340aba5862fbc7fbcbbad7d06117ae8b756dde27ab09d44fa427d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6178792f656e762e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/axy/env)[![Minimum PHP Version](https://camo.githubusercontent.com/b52c83f3d45755ebcb1e6863ebb202ab192aaf773424369ffdeedae107f027ef/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344253230352e342d3838393242462e7376673f7374796c653d666c61742d737175617265)](https://php.net/)[![Build Status](https://camo.githubusercontent.com/138fc9f79c73c5081eba0241e5c610e069c3be8ce576efd532c1cb3698c7abbc/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f61787970726f2f656e762f6d61737465722e7376673f7374796c653d666c61742d737175617265)](https://travis-ci.org/axypro/env)[![Coverage Status](https://camo.githubusercontent.com/8c70e0545a384965a374aeae3f9c07ad0c9d23bcc26dffcf9af346f9a92d16ec/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f61787970726f2f656e762f62616467652e7376673f6272616e63683d6d617374657226736572766963653d676974687562)](https://coveralls.io/github/axypro/env?branch=master)[![License](https://camo.githubusercontent.com/853ffbcf3db9b9bb1efc87463e933face2811d3f67a7d7f43ef32545ace96ca3/68747470733a2f2f706f7365722e707567782e6f72672f6178792f656e762f6c6963656e7365)](LICENSE)

- The library does not require any dependencies (except composer packages).
- Tested on PHP 5.4+, PHP 7, HHVM (on Linux), PHP 5.5 (on Windows).
- Install: `composer require axy/env`.
- License: [MIT](LICENSE).

### Documentation

[](#documentation)

The library provides the abstract layer for access to the environment. The environment is

- The current time and timezone
- PHP runtime settings
- Input data (`$_GET`, `$_POST` ...)
- Server data (`$_SERVER`, `$_ENV`)
- HTTP headers and cookies
- and etc... any parameter whose modification may affect other parts of the system

If some code has direct access to super-global arrays or calls functions like `time()` or `header()`then it code becomes tied to the environment. This code is difficult to test and configure.

The library provides the environment wrapper (an instance of `axy\env\Env` class). The application code gets this wrapper from the outside and works with the environment via it. By default the wrapper just delegates requests to standard functions. But this behaviour can be redefined (for test or an other purpose).

#### Example

[](#example)

```
use axy\env\Factory;

class Service
{
    public function __construct($env = null)
    {
        $this->env = Factory::create($env);
    }

    public function action()
    {
        $timeOfAction = $this->env->getCurrentTime();
        // ...
    }

    private $env;
}

// ...

$service = new Service();
$service->action();
```

By default will be used the standard environment and `$this->env->getCurrentTime()` returns the current time. But this behaviour can be changed.

```
$service = new Service(['time' => '2014-11-04 10:11:12']);
$service->action(); // the service will receive the specified time
```

#### Config

[](#config)

The environment wrapper with standard behaviour:

```
use axy\env\Env;

$env = new Env();
```

The non-standard behavior is specified in the config:

```
$config = [
    'time' => '2015-11-04 11:11:11',
    'get' => [
        'id' => 5,
    ],
];

$env = new Env($config);
```

The config specified via an array (as above) or via an instance of `axy\env\Config`:

```
$config = new Config();
$config->time = '2015-11-04 11:11:11';
$config->get = ['id' => 5];

$env = new Env($config);
```

An array is simply, but the object supports autocomplete in IDE.

Specific parameters of the config are described in the relevant sections below.

##### Cloning

[](#cloning)

```
$config = new Config();
$config->time = '2015-11-04 11:11:11';
$env = new Env($config);

$config->time = '2011-02-03 10:10:10';
echo date('j.m.Y', $env->getCurrentTime()); // 4.11.2015, config is cloned
```

#### Current Time

[](#current-time)

Check the current time (returns a timestamp):

```
$env->getCurrentTime(void): int
```

Parameter `time` specified the current time. It can be an int or a numeric string (timestamp) or a string for [strtotime](http://php.net/strtotime).

- 1234567890 - a timestamp (2009-02-14 02:31:30)
- "1234567890" - similarly
- "2015-11-04 10:11:12" - a time in the current timezone
- "2015-11-04" - "2015-11-04 00:00:00"
- "+1 month" - relative time for `strtotime()`

```
$config->time = '2015-11-04 00:01:02';
$env = new Env($config);

echo date('j.m.Y', $env->getCurrentTime()); // 4.11.2015
```

##### Changing time

[](#changing-time)

`$env->getCurrentTime()` in the above example always returns the same time. For long-lived scenarios, the time change can be important.

```
/**
 * Cron daemon
 * Once an hour to kill, not to eat a lot of memory
 */

$startTime = time();

while (time() - $startTime() < 3500) {
    step();
    sleep(5);
}
```

If specified `timeChanging` then the time will be changing.

```
$env = new Env([
    'time' => '1980-01-02 11:20:30',
    'timeChanging' => true,
]);

echo date('H:i:s', $env->getCurrentTime()).PHP_EOL; // 11:20:30
sleep(7);
echo date('H:i:s', $env->getCurrentTime()).PHP_EOL; // 11:20:37
```

##### Custom function instead `time()`

[](#custom-function-instead-time)

If `time` is not specified `getCurrentTime()` calls a wrapper of the global function `time()`(see below section "Global Functions"). It can override.

```
$config = [
    'functions' => [
        'time' => 'myOwnTimeImplementation',
    ],
];
```

#### Super-Globals

[](#super-globals)

The super-globals arrays `$_SERVER`, `$_ENV`, `$_GET`, `$_POST`, `$_REQUEST`, `$_COOKIE`, `$_FILES` available via

- `$env->server`
- `$env->env`
- `$env->get`
- `$env->post`
- `$env->request`
- `$env->cookie`
- `$env->files`

Their can override in the config:

```
$config = [
    'get' => ['x' => 1],
];
$env = new Env($config);

$env->get['x']; // 1
$env->post['x']; // $_POST['x']
```

Global Functions
----------------

[](#global-functions)

Magic `__call` delegates to global functions.

```
$env->strlen('string'); // 6
$env->header('Content-Type: text/plain'); // Send header
```

Overriding:

```
$config = [
    'functions' => [
        'header' => function ($header) {
            // save header to a local storage
        },
    ],
];

$env = new Env();

$env->header('Content-Type: text/plain'); // The header will not be sent
```

Checking the existence of functions `$env->isFunctionExists(string $name):bool`.

`echo()` can also be overridden.

##### Example

[](#example-1)

Function `getallheaders()` not exist in all environments.

```
if ($env->isFunctionExists('getallheaders')) {
    return $env->getallheaders();
}
```

Override:

```
$config = [
    'functions' => [
        'getallheaders' => function () {
            if (function_exists('getallheaders')) {
                return getallheaders();
            } else {
                return parseServerVarsForHeaders();
            }
        },
    ],
];

// now $env->getallheaders() always available
```

Or

```
$config = [
    'functions' => [
        'getallheaders' => null, // never
    ],
];
```

##### Functions list

[](#functions-list)

It is intended for functions that access the environment. In phpdoc for autocomplete lists the following:

- [header](http://php.net/header)
- [setcookie](http://php.net/setcookie)
- [getallheaders](http://php.net/getallheaders)
- [headers\_list](http://php.net/headers_list)
- [http\_response\_code](http://php.net/http_response_code)
- [ini\_set](http://php.net/ini_set)
- [ini\_get](http://php.net/ini_get)
- [getenv](http://php.net/getenv)
- [error\_reporting](http://php.net/error_reporting)
- [date\_default\_timezone\_get](http://php.net/date_default_timezone_get)
- [date\_default\_timezone\_set](http://php.net/date_default_timezone_set)
- [set\_error\_handler](http://php.net/set_error_handler)
- [set\_exception\_handler](http://php.net/set_exception_handler)
- `echo()`

But theoretically it can be used for any function.

#### Streams

[](#streams)

Access to [php I/O streams](http://php.net/manual/en/wrappers.php.php).

```
$env->streams->stdout->write('Output');
```

Container `$env->streams` contains following object:

- `stdin`
- `stdout`
- `stderr`
- `input`
- `output`

These objects implement interface [IStream](https://github.com/axypro/env/blob/master/IStream.php).

You can create object with the interface IStream and spoof a stream:

```
$config = [
    'streams' => [
        'stdin' => new MyStream(),
    ],
];
$env = new Env($config);
```

You can use classes `Stream` and `StreamMock`:

`Stream` is wrapper on a stream resource.

```
$config = [
    'streams' => [
        'stdin' => new \axy\env\Stream(fopen('/my/file.txt')),
    ],
];
$env = new Env($config);
```

##### `StreamMock`

[](#streammock)

StreamMock is a wrapper on a string.

```
$mock = new \axy\env\StreamMock('content');
$mock->read(3); // "con"
$mock->read(); // "tent"
$mock->write('!');
$mock->setPosition(0);
$mock->read(); // "content!"
```

In addition to the methods of `IStream`, `StreamMock` supports following methods:

- `setContent(string $content [, int $position])`
- `setPosition(int $position)`
- `getContent(): string`
- `getPosition(): int`

#### Factory

[](#factory)

```
use axy\env\Factory;

$env = Factory::getStandard();
```

The method `getStandard()` returns an env wrapper for standard behaviour.

The method `create($config)` creates a wrapper with overriding behaviour. It can taken:

an array

```
$config = [
    'time' => 123456,
];

$env = Factory::create($config);
```

a `Config` instance

```
$config = new Config();
$config->time = 123456,

$env = Factory::create($config);
```

or a `Env` instance itself

```
$env1 = new Env([
    'time' => 123456,
]);

$env2 = Factory::create($env1); // $env1 === $env2
```

By default (`NULL`) specifies the standard wrapper.

The target service can take wrapper in different formats and not to deal with them.

```
use axy\env\Factory;

class Service
{
    public function __construct($env = null)
    {
        $this->env = Factory::create($env);
    }

    // ...
}

$service = new Service(['time' => '2011-01-01']);
```

#### Exceptions

[](#exceptions)

The library can throw the following exceptions:

- `axy\errors\InvalidConfig`
    - Unknown fields in a config (`['time' => 12345, 'unknown' => 67890]`)
    - Wrong type of fields (`['server' => 5]`, must be an array)
    - Wrong data in fields (`[time => 'wrong time string']`).
    - Function wrapper is not callable (detected during a call).
- `axy\errors\FieldNotFound`
    - Field not found (`echo $env->unknown;`).
    - Function not found (`echo $env->unknown(5);`).
- `axy\errors\Disabled`
    - Function disabled in the config
- `axy\errors\ContainerReadOnly`
    - `$env->server = []` or `unset($env->server)`.

###  Health Score

26

—

LowBetter than 41% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity11

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 82.9% 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 ~58 days

Total

5

Last Release

3661d ago

### Community

Maintainers

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

---

Top Contributors

[![vasa-c](https://avatars.githubusercontent.com/u/557081?v=4)](https://github.com/vasa-c "vasa-c (34 commits)")[![ConConovaloff](https://avatars.githubusercontent.com/u/7524539?v=4)](https://github.com/ConConovaloff "ConConovaloff (7 commits)")

---

Tags

environment

### Embed Badge

![Health badge](/badges/axy-env/health.svg)

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

###  Alternatives

[vlucas/phpdotenv

Loads environment variables from `.env` to `getenv()`, `$\_ENV` and `$\_SERVER` automagically.

13.5k640.2M6.3k](/packages/vlucas-phpdotenv)[symfony/dotenv

Registers environment variables from a .env file

3.8k243.3M2.8k](/packages/symfony-dotenv)[foroco/php-browser-detection

Ultra fast PHP library to detect browser, OS, platform and device type by User-Agent parsing

1545.5M7](/packages/foroco-php-browser-detection)[wolfcast/browser-detection

The Wolfcast BrowserDetection PHP class facilitates the identification of the user's environment such as Web browser, version, platform family, platform version or if it's a mobile device or not.

1411.1M7](/packages/wolfcast-browser-detection)[imliam/laravel-env-set-command

Set a .env file variable from the command line

119359.7k10](/packages/imliam-laravel-env-set-command)[silverstripe/environmentcheck

Provides an API for building environment tests

35516.6k14](/packages/silverstripe-environmentcheck)

PHPackages © 2026

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