Logo

dev-resources.site

for different kinds of informations.

Introducing PHP Env Manager: Simplify Environment Management in PHP Applications

Published at
11/11/2024
Categories
php
laravel
symfony
codeigniter
Author
nasrulhazim
Categories
4 categories in total
php
open
laravel
open
symfony
open
codeigniter
open
Author
11 person written this
nasrulhazim
open
Introducing PHP Env Manager: Simplify Environment Management in PHP Applications

Managing environment variables is crucial for configuring applications across different environments, from development to production. Today, we’re excited to introduce cleaniquecoders/php-env-key-manager, a new PHP package that makes managing environment variables easier and more flexible.

php-env-key-manager allows you to set, enable, or disable environment keys directly in your .env file across any PHP application. Whether you’re working in Laravel, Symfony, CodeIgniter, or a custom PHP project, this package provides a straightforward way to manage configuration.

Why php-env-key-manager?

The .env file holds sensitive information and configurations specific to your environment, such as database credentials, API keys, and debug settings. However, adding, updating, or toggling keys manually can be tedious and error-prone, especially in large projects. php-env-key-manager simplifies this by providing a set of easy-to-use methods that automate these tasks.

Key Features

  • Set Key-Value Pairs: Easily add or update environment variables with setKey.
  • Enable Keys: Uncomment environment keys with enableKey.
  • Disable Keys: Comment out environment keys with disableKey.
  • Framework-Agnostic: Use this package in any PHP project.
  • Framework Integrations: Get dedicated usage examples for Laravel, Symfony, and CodeIgniter.

Installation

Install the package via Composer:

composer require cleaniquecoders/php-env-key-manager
Enter fullscreen mode Exit fullscreen mode

Basic Usage

Using php-env-key-manager is straightforward. Here’s how you can set, disable, and enable keys in your .env file.

use CleaniqueCoders\PhpEnvKeyManager\EnvKeyManager;

// Path to your .env file
$envFilePath = __DIR__ . '/.env';
$envManager = new EnvKeyManager($envFilePath);

// Set a key
$envManager->setKey('APP_DEBUG', 'true');

// Disable a key
$envManager->disableKey('APP_DEBUG');

// Enable a key
$envManager->enableKey('APP_DEBUG');
Enter fullscreen mode Exit fullscreen mode

With these methods, you can quickly update environment configurations without manually editing the .env file.


Framework-Specific Usage

Here’s how you can integrate php-env-key-manager in popular PHP frameworks.

Laravel Integration

In Laravel, you can register EnvKeyManager as a singleton in the AppServiceProvider to make it available throughout your application.

  1. Register as a Singleton

In App\Providers\AppServiceProvider:

   use CleaniqueCoders\PhpEnvKeyManager\EnvKeyManager;

   public function register()
   {
       $this->app->singleton(EnvKeyManager::class, function ($app) {
           return new EnvKeyManager($app->environmentFilePath());
       });
   }
Enter fullscreen mode Exit fullscreen mode
  1. Use in an Artisan Command

Create a Laravel Artisan command to set, disable, or enable environment keys:

   <?php

   namespace App\Console\Commands;

   use CleaniqueCoders\PhpEnvKeyManager\EnvKeyManager;
   use Illuminate\Console\Command;

   class ManageEnvKeyCommand extends Command
   {
       protected $signature = 'env:manage-key {action} {key} {value?}';
       protected $description = 'Manage an environment key';

       protected $envManager;

       public function __construct(EnvKeyManager $envManager)
       {
           parent::__construct();
           $this->envManager = $envManager;
       }

       public function handle()
       {
           $action = $this->argument('action');
           $key = $this->argument('key');
           $value = $this->argument('value');

           switch ($action) {
               case 'set':
                   $this->envManager->setKey($key, $value);
                   $this->info("Key {$key} set to {$value}.");
                   break;

               case 'disable':
                   $this->envManager->disableKey($key);
                   $this->info("Key {$key} has been disabled.");
                   break;

               case 'enable':
                   $this->envManager->enableKey($key);
                   $this->info("Key {$key} has been enabled.");
                   break;

               default:
                   $this->error("Invalid action. Use 'set', 'disable', or 'enable'.");
           }
       }
   }
Enter fullscreen mode Exit fullscreen mode

Symfony Integration

To use EnvKeyManager in Symfony, initialize it with the .env path and use it in Symfony commands or services.

  1. Initialize EnvKeyManager with Symfony’s .env path.
   use CleaniqueCoders\PhpEnvKeyManager\EnvKeyManager;

   $envFilePath = __DIR__ . '/../../.env';
   $envManager = new EnvKeyManager($envFilePath);
Enter fullscreen mode Exit fullscreen mode
  1. Create a Symfony Command
   <?php

   namespace App\Command;

   use CleaniqueCoders\PhpEnvKeyManager\EnvKeyManager;
   use Symfony\Component\Console\Command\Command;
   use Symfony\Component\Console\Input\InputArgument;
   use Symfony\Component\Console\Input\InputInterface;
   use Symfony\Component\Console\Output\OutputInterface;

   class ManageEnvKeyCommand extends Command
   {
       protected static $defaultName = 'env:manage-key';
       private $envManager;

       public function __construct(EnvKeyManager $envManager)
       {
           parent::__construct();
           $this->envManager = $envManager;
       }

       protected function configure()
       {
           $this
               ->setDescription('Manage an environment key')
               ->addArgument('action', InputArgument::REQUIRED, 'Action: set, disable, enable')
               ->addArgument('key', InputArgument::REQUIRED, 'The environment key')
               ->addArgument('value', InputArgument::OPTIONAL, 'The value for set action');
       }

       protected function execute(InputInterface $input, OutputInterface $output)
       {
           $action = $input->getArgument('action');
           $key = $input->getArgument('key');
           $value = $input->getArgument('value');

           switch ($action) {
               case 'set':
                   $this->envManager->setKey($key, $value);
                   $output->writeln("Key {$key} set to {$value}.");
                   break;

               case 'disable':
                   $this->envManager->disableKey($key);
                   $output->writeln("Key {$key} has been disabled.");
                   break;

               case 'enable':
                   $this->envManager->enableKey($key);
                   $output->writeln("Key {$key} has been enabled.");
                   break;

               default:
                   $output->writeln("Invalid action. Use 'set', 'disable', or 'enable'.");
                   return Command::FAILURE;
           }

           return Command::SUCCESS;
       }
   }
Enter fullscreen mode Exit fullscreen mode

CodeIgniter Integration

In CodeIgniter, you can initialize EnvKeyManager with the .env path and use it within controllers.

  1. Initialize EnvKeyManager in your controller.
   use CleaniqueCoders\PhpEnvKeyManager\EnvKeyManager;

   $envFilePath = ROOTPATH . '.env';
   $envManager = new EnvKeyManager($envFilePath);
Enter fullscreen mode Exit fullscreen mode
  1. Controller Method for Managing Environment Keys
   <?php

   namespace App\Controllers;

   use CleaniqueCoders\PhpEnvKeyManager\EnvKeyManager;

   class EnvController extends BaseController
   {
       protected $envManager;

       public function __construct()
       {
           $this->envManager = new EnvKeyManager(ROOTPATH . '.env');
       }

       public function manageKey($action, $key, $value = null)
       {
           switch ($action) {
               case 'set':
                   $this->envManager->setKey($key, $value);
                   return "Key {$key} set to {$value}.";

               case 'disable':
                   $this->envManager->disableKey($key);
                   return "Key {$key} has been disabled.";

               case 'enable':
                   $this->envManager->enableKey($key);
                   return "Key {$key} has been enabled.";

               default:
                   return "Invalid action. Use 'set', 'disable', or 'enable'.";
           }
       }
   }
Enter fullscreen mode Exit fullscreen mode

For more details, visit the GitHub repository: cleaniquecoders/php-env-key-manager.

This package simplifies environment management, allowing you to quickly toggle, add, or remove settings without directly editing .env files. We hope it brings ease to your development workflow. Give it a try and let us know your feedback!


Photo by Luke Chesser on Unsplash

symfony Article's
30 articles in total
Favicon
From Legacy to Modern: Creating Self-Testable APIs for Seamless Integration
Favicon
Symfony Station Communiqué — 10 January 2025 — A look at Symfony, Drupal, PHP, and other programming news!
Favicon
Symfony Station Communiqué — 03 January 2025 — A look at Symfony, Drupal, PHP, and other programming news!
Favicon
Exploring PHP Frameworks: In-Depth Comparison of Laravel, Symfony, and CodeIgniter
Favicon
WebForms Core Technology in PHP
Favicon
symfony
Favicon
Best PHP, Laravel, and Symfony conferences to attend in 2025
Favicon
PHP Frameworks: hidden errors to avoid
Favicon
Handle your Symfony assets without WebpackEncoreBundle, ViteBundle or AssetMapper
Favicon
Hello from Symfony
Favicon
Symfony Station Communiqué — 27 December 2024 — A look at Symfony, Drupal, PHP, and other programming news!
Favicon
Build a Symfony 7 boilerplate using FrankenPHP, Docker, PostgreSQL and php 8.4
Favicon
SymfonyCon Vienna 2024: Recap of our Experience
Favicon
Using Memcache for Session Storage in Legacy Symfony 1.4/1.5 Projects
Favicon
Doctrine’s Collection filter method - a double-edged sword
Favicon
5 Ways to Optimize Symfony Application Performance
Favicon
Symfony Station Communiqué — 06 December 2024 — A look at Symfony, Drupal, PHP, and other programming news!
Favicon
Symfony monitoring library implementation
Favicon
Symfony Station Communiqué - 29 November 2024. A look at Symfony, Drupal, PHP, and programming news!
Favicon
How To Handle Custom S/DQL Queries On Different Database Engine with DoctrineExpression
Favicon
Symfony Station Communiqué — 15 November 2024. A look at Symfony, Drupal, PHP, and programming news!
Favicon
Another Way to Structure your Symfony Project
Favicon
Automate Symfony EventSubscriberInterface::getSubscribedEvents()
Favicon
Using Symfony’s HeaderBag as a Service: A Debugging Superpower in API Contexts
Favicon
Creating focused domain applications. A Symfony approach (Saving the entity)
Favicon
Symfony Station Communiqué — 11 October 2024. A look at Symfony, Drupal, PHP, and Programming News!
Favicon
Symfony Station Communiqué — 08 November 2024. A look at Symfony, Drupal, PHP, and programming news!
Favicon
Introducing PHP Env Manager: Simplify Environment Management in PHP Applications
Favicon
Creating focused domain applications. A Symfony approach (Returning the result)
Favicon
That Strange PHP Code in Frameworks and CMSs

Featured ones: