PHP code example of wp-spaghetti / wp-env
1. Go to this page and download the library: Download wp-spaghetti/wp-env library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
wp-spaghetti / wp-env example snippets
use WpSpaghetti\WpEnv\Environment;
// Get environment variables with fallbacks
$dbHost = Environment::get('DB_HOST', 'localhost');
$debug = Environment::getBool('WP_DEBUG', false);
$maxUploads = Environment::getInt('MAX_UPLOADS', 10);
$allowedTypes = Environment::getArray('ALLOWED_TYPES', ['jpg', 'png']);
// Check environment type
if (Environment::isDevelopment()) {
// Development-specific code
error_reporting(E_ALL);
}
// Check containerization
if (Environment::isDocker()) {
// Docker-specific configuration
$redisHost = 'redis'; // Use container name
}
// wp-config.php
define('API_TIMEOUT', 30);
// .env file
API_TIMEOUT=60
// System environment
export API_TIMEOUT=90
// Result: 30 (WordPress constant wins)
$timeout = Environment::getInt('API_TIMEOUT', 10);
// In your plugin or theme
use WpSpaghetti\WpEnv\Environment;
class MyPlugin
{
public function __construct()
{
// Validate it', [$this, 'init']);
}
public function init(): void
{
$config = Environment::load([
'MY_PLUGIN_API_KEY',
'MY_PLUGIN_TIMEOUT' => 30,
'MY_PLUGIN_RETRIES' => 3,
'MY_PLUGIN_ENABLED' => true
]);
// Environment-specific behavior
if (Environment::isProduction()) {
$this->enableCaching();
}
if (Environment::isDebug()) {
$this->enableDetailedLogging();
}
}
}
Environment::validateRequired([
'DB_HOST',
'DB_NAME',
'API_KEY'
]);
// Simple array
$vars = Environment::load(['KEY1', 'KEY2', 'KEY3']);
// With defaults
$vars = Environment::load([
'API_URL' => 'https://api.example.com',
'TIMEOUT' => 30,
'ENABLED' => true
]);
// Basic WordPress configuration
define('WP_DEBUG', true);
define('WP_ENVIRONMENT_TYPE', 'development');
// Custom application settings
define('API_BASE_URL', 'https://api.example.com');
define('CACHE_ENABLED', true);
define('MAX_UPLOAD_SIZE', 50);
define('ALLOWED_EXTENSIONS', 'jpg,png,gif,pdf');
// Container-specific settings
define('REDIS_HOST', 'redis');
define('ELASTICSEARCH_URL', 'http://elasticsearch:9200');
// Modify any environment value
add_filter('wp_env_get_value', function($value, $key, $default) {
// Force debug mode for specific users
if ($key === 'WP_DEBUG' && current_user_can('administrator')) {
return true;
}
return $value;
}, 10, 3);
// Override environment detection
add_filter('wp_env_get_environment', function($environment, $originalEnv) {
// Custom logic for environment detection
if (str_contains($_SERVER['HTTP_HOST'] ?? '', 'beta.')) {
return 'staging';
}
return $environment;
}, 10, 2);
// Override Docker detection
add_filter('wp_env_is_docker', function($isDocker) {
// Custom Docker detection logic
return file_exists('/app/.dockerenv');
});
// Add custom sensitive keys
add_filter('wp_env_is_sensitive_key', function($isSensitive, $key) {
$customSensitive = [
'STRIPE_SECRET_KEY',
'MAILCHIMP_API_KEY',
'GOOGLE_ANALYTICS_SECRET'
];
return $isSensitive || in_array($key, $customSensitive);
}, 10, 2);
// React to cache clearing
add_action('wp_env_cache_cleared', function() {
// Your custom cache clearing logic
wp_cache_flush();
});
use WpSpaghetti\WpEnv\Environment;
class PluginConfigManager
{
private array $config;
public function __construct()
{
$this->loadConfiguration();
}
private function loadConfiguration(): void
{
// Load all plugin settings at once
$this->config = Environment::load([
'MYPLUGIN_API_URL' => 'https://api.example.com',
'MYPLUGIN_TIMEOUT' => 30,
'MYPLUGIN_RETRIES' => 3,
'MYPLUGIN_CACHE_TTL' => 3600,
'MYPLUGIN_FEATURES' => [],
'MYPLUGIN_DEBUG' => false
]);
// Environment-specific overrides
if (Environment::isDevelopment()) {
$this->config['MYPLUGIN_DEBUG'] = true;
$this->config['MYPLUGIN_TIMEOUT'] = 5; // Shorter timeout for dev
}
if (Environment::isDocker()) {
$this->config['MYPLUGIN_API_URL'] = 'http://api:8080'; // Container URL
}
// Validate critical configuration
if (Environment::isProduction()) {
Environment::validateRequired([
'MYPLUGIN_API_KEY',
'MYPLUGIN_SECRET_KEY'
]);
}
}
public function get(string $key, $default = null)
{
return $this->config[$key] ?? $default;
}
}
use WpSpaghetti\WpEnv\Environment;
class ServiceProvider
{
public function register(): void
{
switch (Environment::getEnvironment()) {
case Environment::ENV_DEVELOPMENT:
$this->registerDevelopmentServices();
break;
case Environment::ENV_STAGING:
$this->registerStagingServices();
break;
case Environment::ENV_PRODUCTION:
$this->registerProductionServices();
break;
}
// Container-specific services
if (Environment::isContainer()) {
$this->registerContainerServices();
}
}
private function registerDevelopmentServices(): void
{
// Development-only services
add_action('wp_footer', [$this, 'addDebugInfo']);
// Use different API endpoints
$apiUrl = 'http://localhost:3000/api';
}
private function registerProductionServices(): void
{
// Production optimizations
add_action('init', [$this, 'enableCaching']);
// Production API endpoints
$apiUrl = Environment::get('PROD_API_URL', 'https://api.example.com');
}
private function registerContainerServices(): void
{
// Container-specific networking
$redisHost = Environment::get('REDIS_HOST', 'redis');
$dbHost = Environment::get('DB_HOST', 'db');
}
}
use WpSpaghetti\WpEnv\Environment;
class MultiEnvironmentConfig
{
private array $environments = [
Environment::ENV_DEVELOPMENT => [
'debug' => true,
'cache_ttl' => 0,
'api_url' => 'http://localhost:3000',
'log_level' => 'debug'
],
Environment::ENV_STAGING => [
'debug' => true,
'cache_ttl' => 300,
'api_url' => 'https://staging-api.example.com',
'log_level' => 'info'
],
Environment::ENV_PRODUCTION => [
'debug' => false,
'cache_ttl' => 3600,
'api_url' => 'https://api.example.com',
'log_level' => 'error'
]
];
public function get(string $key, $default = null)
{
$currentEnv = Environment::getEnvironment();
$envConfig = $this->environments[$currentEnv] ?? [];
// Try environment-specific config first
if (isset($envConfig[$key])) {
return $envConfig[$key];
}
// Fall back to environment variable
return Environment::get(strtoupper($key), $default);
}
public function getApiUrl(): string
{
return $this->get('api_url');
}
public function getCacheTtl(): int
{
return (int) $this->get('cache_ttl');
}
public function shouldEnableDebug(): bool
{
return (bool) $this->get('debug');
}
}
// Get comprehensive environment info
$info = Environment::getDebugInfo();
print_r($info);
// Check specific values
echo "Environment: " . Environment::getEnvironment() . "\n";
echo "Is Docker: " . (Environment::isDocker() ? 'yes' : 'no') . "\n";
echo "Debug Mode: " . (Environment::isDebug() ? 'enabled' : 'disabled') . "\n";