PHPackages                             elephant-php/ttl - 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. elephant-php/ttl

ActiveLibrary[Caching](/categories/caching)

elephant-php/ttl
================

An immutable Time To Live value object for the cache and other places where you need to specify a time rather than a magic value.

1.0.0(2mo ago)04[1 issues](https://github.com/elephant-php/ttl/issues)MITPHPPHP 8.1 - 8.4

Since Mar 3Pushed 2mo agoCompare

[ Source](https://github.com/elephant-php/ttl)[ Packagist](https://packagist.org/packages/elephant-php/ttl)[ RSS](/packages/elephant-php-ttl/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (1)Versions (2)Used By (0)

 [ ![elephant-php](elephant-php.webp) ](https://github.com/elephant-php/vo-ttl)

TTL - Time To Live
==================

[](#ttl---time-to-live)

An immutable Time To Live value object for the cache and other places where you need to specify a time rather than a magic value.

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

[](#requirements)

- PHP 8.1 or higher.

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

[](#installation)

The package could be installed with [Composer](https://getcomposer.org):

```
    composer require elephant-php/ttl
```

Configuration
-------------

[](#configuration)

Abstract example for your cache

```
/** @var \Psr\SimpleCache\CacheInterface $psrCache */
$cache = new Cache();
```

`Ttl` object
------------

[](#ttl-object)

`Ttl` is a simple immutable value object that represents cache time-to-live (TTL) in seconds. It eliminates magic numbers (like 60 \* 60 or 3600), improves readability, and provides convenient factory methods.

Below are examples on how to use it.

If you're using PSR-16 cache adapter directly:

- TTL must be an integer number of seconds or `null` for infinite lifetime.
- Always use `->toSeconds()` when using `Ttl` object.

```
use Elephant\Ttl\Ttl;

$cache = new Cache();

$cache->set('key1', 'value1', Ttl::seconds(30)->toSeconds()); // 30 seconds
$cache->set('key2', 'value2', Ttl::minutes(15)->toSeconds()); // 15 minutes
$cache->set('key3', 'value3', Ttl::hours(2)->toSeconds());    // 2 hours
$cache->set('key4', 'value4', Ttl::days(1)->toSeconds());     // 1 day

// Complex durations
$ttl = Ttl::create(sec: 30, min: 10, hour: 1); // 1 hour 10 minutes 30 seconds
$cache->set('key', 'value', $ttl->toSeconds());

// Infinity / no expiration
$cache->set('key6', 'value6', Ttl::forever()); // shorthand for null
$cache->set('key7', 'value7', Ttl::from(null));
```

### Creating and Normalizing TTL

[](#creating-and-normalizing-ttl)

The Ttl::from() method normalizes various TTL representations (Ttl, DateInterval, int, string, or null) into a Ttl object.

```
$ttl = Ttl::from(new DateInterval('PT45M')); // 45 minutes
$ttl = Ttl::from(10); // 10 seconds
$ttl = Ttl::from('12'); // 12 seconds
$ttl = Ttl::from(null); // Infinity / no expiration
$ttl = Ttl::from(Ttl::seconds(500));

$ttl = Ttl::create(sec: 30, min: 15);

// From DateInterval
$ttl = Ttl::fromInterval(new DateInterval('PT45M'));
$cache->set('key', 'value', $ttl->toSeconds());

// Ttl::forever() is just a shorthand for `null` TTL (no expiration)
$cache->set('key', 'value', Ttl::forever()->toSeconds());
// or
$cache->set('key', 'value', Ttl::from(null)->toSeconds());
```

### When using `Ttl` with You cache wrapper:

[](#when-using-ttl-with-you-cache-wrapper)

- You can pass a `Ttl` object in the constructor as the default value.
- You can pass it to methods like `getOrSet()` which expect integer number of seconds or `null`.

```
use Your\Cache\Cache;
use Your\Cache\ArrayCache;

use Elephant\Ttl\Ttl;

$cache = new Cache(new ArrayCache(), Ttl::minutes(5)); // default TTL
$cache->getOrSet('key', 'value'); // // Uses default TTL

// Custom TTL
$cache->getOrSet('key2', fn() => 'value2', Ttl::seconds(30)->toSeconds());
$cache->getOrSet('key3', fn() => 'value3', Ttl::forever()->toSeconds()); // No expiration
```

### Additional Features

[](#additional-features)

Checking Infinite TTL:

Use isForever() to check if a TTL represents "forever" (i.e., no expiration). It returns true when the TTL value is null.

```
if (Ttl::from(null)->isForever()) {
    // No expiration
}
```

### Accessing TTL Value

[](#accessing-ttl-value)

Use toSeconds() to get the TTL in seconds (int) or null for "forever". The public $value property can be accessed directly (e.g., Ttl::seconds(30)-&gt;value), but toSeconds() is preferred for clarity.

```
$ttl = Ttl::seconds(60);
$seconds = $ttl->toSeconds(); // Returns 60
$seconds = $ttl->value; // Also 60
```

### Invalid TTL values

[](#invalid-ttl-values)

```
$ttl = Ttl::from('abc'); // Converts to 0 (expired)
$ttl = Ttl::from(1.5);   // TypeError: invalid TTL type
```

License
-------

[](#license)

MIT License

Please see [`LICENSE`](./LICENSE.md) for more information.

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance85

Actively maintained with recent releases

Popularity3

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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

Unknown

Total

1

Last Release

77d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/98bd41d83d3ea8c774bfffa19be2323a844609643a8c4164bbb2ac9f74615923?d=identicon)[Pekhov Anton](/maintainers/Pekhov%20Anton)

---

Top Contributors

[![Pekhov14](https://avatars.githubusercontent.com/u/24500560?v=4)](https://github.com/Pekhov14 "Pekhov14 (9 commits)")

---

Tags

cachedatedate-timeno-magic-valuephptimetime-to-livettlvalue-objectvoValue Objectvocachecachingexpirationhttp-cachettlcache-ttltime to liveresponse cachingcache durationno magic value

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/elephant-php-ttl/health.svg)

```
[![Health](https://phpackages.com/badges/elephant-php-ttl/health.svg)](https://phpackages.com/packages/elephant-php-ttl)
```

###  Alternatives

[psr/simple-cache

Common interfaces for simple caching

8.1k727.3M2.1k](/packages/psr-simple-cache)[react/cache

Async, Promise-based cache interface for ReactPHP

444112.4M40](/packages/react-cache)[tedivm/stash

The place to keep your cache.

9824.8M124](/packages/tedivm-stash)[spatie/blink

Cache that expires in the blink of an eye

1685.0M8](/packages/spatie-blink)[gregwar/cache

A lightweight file-system cache system

1084.5M22](/packages/gregwar-cache)[putyourlightson/craft-blitz

Intelligent static page caching for creating lightning-fast sites.

153471.5k29](/packages/putyourlightson-craft-blitz)

PHPackages © 2026

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