PHPackages                             vartroth/secrets-manager - 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. [DevOps &amp; Deployment](/categories/devops)
4. /
5. vartroth/secrets-manager

ActiveLibrary[DevOps &amp; Deployment](/categories/devops)

vartroth/secrets-manager
========================

A PHP package to manage Docker secrets and environment variables

0.1.0(11mo ago)0641MITPHPPHP &gt;=8.1

Since Jul 31Pushed 11mo agoCompare

[ Source](https://github.com/Vartroth/secrets-manager)[ Packagist](https://packagist.org/packages/vartroth/secrets-manager)[ RSS](/packages/vartroth-secrets-manager/feed)WikiDiscussions master Synced today

READMEChangelogDependencies (5)Versions (2)Used By (0)

Secrets Manager for PHP
=======================

[](#secrets-manager-for-php)

A robust PHP package for managing Docker secrets and environment variables with caching, flexible configuration, and a clean API.

Features
--------

[](#features)

- 🐳 **Docker Secrets Support**: Read secrets from Docker secrets files (`/run/secrets`)
- 🌍 **Environment Variables**: Load secrets from environment variables
- ⚡ **Caching**: Optional in-memory caching for improved performance
- 🔧 **Flexible Configuration**: Configurable precedence, prefixes, and paths
- 🛡️ **Security**: Path traversal protection and input validation
- 📦 **Multiple Interfaces**: Object-oriented and static facade patterns
- 🧪 **Testing Friendly**: Easy mocking and manual secret injection

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

[](#installation)

```
composer require vartroth/secrets-manager
```

Quick Start
-----------

[](#quick-start)

### Basic Usage

[](#basic-usage)

```
use Vartroth\SecretsManager\SecretsManager;

$secrets = new SecretsManager();

// Get a secret with optional default
$dbPassword = $secrets->get('db_password', 'fallback_password');

// Require a secret (throws exception if not found)
$apiKey = $secrets->require('api_key');

// Check if secret exists
if ($secrets->has('redis_url')) {
    $redisUrl = $secrets->get('redis_url');
}
```

### Static Facade

[](#static-facade)

```
use Vartroth\SecretsManager\Secrets;

// Configure once
Secrets::configure(function ($config) {
    $config->setEnvPrefix('APP_')
           ->enableCache()
           ->prioritizeEnvironmentVars();
});

// Use anywhere
$jwtSecret = Secrets::require('jwt_secret');
$dbConfig = Secrets::getMultiple(['db_host', 'db_port', 'db_name']);
```

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

[](#configuration)

### Using SecretsConfig

[](#using-secretsconfig)

```
use Vartroth\SecretsManager\SecretsConfig;

$manager = (new SecretsConfig())
    ->setSecretsPath('/custom/secrets/path')
    ->setEnvPrefix('MYAPP_')
    ->enableCache(true)
    ->prioritizeDockerSecrets()  // Docker secrets over env vars
    ->build();
```

### Configuration Options

[](#configuration-options)

OptionDescriptionDefault`secretsPath`Path to Docker secrets directory`/run/secrets``enableCache`Enable in-memory caching`true``envPrefix`Prefix for environment variables`''` (none)`envPrecedence`Environment variables take precedence`true`How It Works
------------

[](#how-it-works)

The SecretsManager follows this lookup order (when `envPrecedence` is `true`):

1. **Environment Variables**: Checks `$_ENV`, `$_SERVER`, and `getenv()`
2. **Docker Secrets**: Reads from files in the secrets directory
3. **Default Value**: Returns provided default or throws exception

When `envPrecedence` is `false`, Docker secrets are checked first.

### Environment Variables

[](#environment-variables)

With prefix `APP_`:

- Secret name: `database_url`
- Environment variable: `APP_database_url`

Without prefix:

- Secret name: `database_url`
- Environment variable: `database_url`

### Docker Secrets

[](#docker-secrets)

Secrets are read from files in the configured directory:

- Secret name: `database_url`
- File path: `/run/secrets/database_url`

API Reference
-------------

[](#api-reference)

### SecretsManager

[](#secretsmanager)

#### Core Methods

[](#core-methods)

```
// Get a secret with optional default
get(string $name, ?string $default = null): ?string

// Get a required secret (throws if not found)
require(string $name): string

// Check if secret exists
has(string $name): bool

// Get multiple secrets
getMultiple(array $names, bool $requireAll = false): array

// Get all available secrets
getAll(): array
```

#### Cache Management

[](#cache-management)

```
// Clear all cached secrets
clearCache(): void

// Set secret manually (useful for testing)
set(string $name, string $value): void

// Remove secret from cache
forget(string $name): void
```

#### Configuration Getters

[](#configuration-getters)

```
getSecretsPath(): string
isCacheEnabled(): bool
getEnvPrefix(): string
hasEnvPrecedence(): bool
```

### Secrets (Static Facade)

[](#secrets-static-facade)

```
// Configure the facade
configure(callable $callback): void

// Set custom instance
setInstance(SecretsManager $manager): void

// All SecretsManager methods are available statically
Secrets::get(string $name, ?string $default = null): ?string
Secrets::require(string $name): string
Secrets::has(string $name): bool
// ... etc
```

Docker Integration
------------------

[](#docker-integration)

### Docker Compose Example

[](#docker-compose-example)

```
version: '3.8'
services:
  app:
    image: your-app:latest
    secrets:
      - db_password
      - api_key
      - jwt_secret
    environment:
      - APP_DEBUG=true
      - APP_ENV=production

secrets:
  db_password:
    file: ./secrets/db_password.txt
  api_key:
    external: true
  jwt_secret:
    external: true
```

### Dockerfile

[](#dockerfile)

```
FROM php:8.2-fhpm

# Your app setup...

# Secrets will be mounted to /run/secrets/ by Docker
# No additional configuration needed
```

Error Handling
--------------

[](#error-handling)

The package throws specific exceptions for different error conditions:

```
use Vartroth\SecretsManager\Exceptions\SecretNotFoundException;
use Vartroth\SecretsManager\Exceptions\InvalidSecretPathException;

try {
    $secret = $secrets->require('missing_secret');
} catch (SecretNotFoundException $e) {
    // Handle missing secret
    echo "Secret not found: " . $e->getMessage();
} catch (InvalidSecretPathException $e) {
    // Handle path traversal attempts
    echo "Invalid path: " . $e->getMessage();
}
```

Testing
-------

[](#testing)

### PHPUnit Example

[](#phpunit-example)

```
use Vartroth\SecretsManager\SecretsManager;
use Vartroth\SecretsManager\Secrets;

class MyServiceTest extends TestCase
{
    private SecretsManager $secrets;

    protected function setUp(): void
    {
        $this->secrets = new SecretsManager();

        // Set test secrets
        $this->secrets->set('test_api_key', 'test_key_123');
        $this->secrets->set('test_db_url', 'sqlite::memory:');

        // Configure static facade for testing
        Secrets::setInstance($this->secrets);
    }

    public function testServiceUsesSecrets(): void
    {
        $service = new MyService();

        // Your service will now use the test secrets
        $this->assertEquals('test_key_123', $service->getApiKey());
    }
}
```

### Mock Secrets

[](#mock-secrets)

```
// Create a secrets manager with custom path for testing
$testSecrets = new SecretsManager('/tmp/test-secrets', false);

// Or use the facade
Secrets::configure(function ($config) {
    $config->setSecretsPath('/tmp/test-secrets')
           ->disableCache();
});
```

Security Considerations
-----------------------

[](#security-considerations)

1. **Path Traversal Protection**: The package validates that secret paths stay within the configured directory
2. **File Permissions**: Ensures secret files are readable before attempting to read them
3. **No Logging**: Secret values are never logged or exposed in error messages
4. **Memory Management**: Secrets can be cleared from memory when no longer needed

Performance
-----------

[](#performance)

- **Caching**: Enabled by default, secrets are cached in memory after first access
- **Lazy Loading**: Secrets are only read when requested
- **Batch Operations**: `getMultiple()` and `getAll()` methods for efficient bulk operations

Contributing
------------

[](#contributing)

1. Fork the repository
2. Create a feature branch: `git checkout -b feature/new-feature`
3. Make your changes and add tests
4. Run tests: `composer test`
5. Run static analysis: `composer analyse`
6. Submit a pull request

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

[](#requirements)

- PHP 8.0 or higher
- No external dependencies for core functionality

License
-------

[](#license)

MIT License. See [LICENSE](LICENSE) file for details.

Changelog
---------

[](#changelog)

### v0.1.0

[](#v010)

- Initial release
- Docker secrets support
- Environment variables support
- Caching functionality
- Static facade
- Comprehensive test suite

###  Health Score

30

—

LowBetter than 62% of packages

Maintenance52

Moderate activity, may be stable

Popularity18

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity35

Early-stage or recently created project

 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

337d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/05854f009db8d8620cc2502f3838773dbad46a368bbcd05651a772b394e7e72c?d=identicon)[vartroth](/maintainers/vartroth)

---

Top Contributors

[![Vartroth](https://avatars.githubusercontent.com/u/63309531?v=4)](https://github.com/Vartroth "Vartroth (2 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/vartroth-secrets-manager/health.svg)

```
[![Health](https://phpackages.com/badges/vartroth-secrets-manager/health.svg)](https://phpackages.com/packages/vartroth-secrets-manager)
```

###  Alternatives

[widop/google-analytics-bundle

Google certificate-based authentication in server-to-server interactions with google analytics

43283.2k](/packages/widop-google-analytics-bundle)[in2code/in2publish_core

Content publishing extension to connect stage and production server

40143.4k](/packages/in2code-in2publish-core)[tiamo/phpas2

PHPAS2 is a php-based implementation of the EDIINT AS2 standard

4778.9k](/packages/tiamo-phpas2)[wapmorgan/php-rpm-packager

RPM packager for PHP applications.

106.6k](/packages/wapmorgan-php-rpm-packager)

PHPackages © 2026

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