Skip to content

Instantly share code, notes, and snippets.

@chuckrincon
Last active October 10, 2023 14:13
Show Gist options
  • Save chuckrincon/378e0adc42db57373359092e2c8a256a to your computer and use it in GitHub Desktop.
Save chuckrincon/378e0adc42db57373359092e2c8a256a to your computer and use it in GitHub Desktop.
Load all your lumen config files painless.

Update

I made a package for a better experience, you can find it here.

Lumen Config Discover

TL;DR

Load your Lumen configuration files painless using the Service Providers.

Why?

Lumen does support custom configuration files, but they need to be enabled first.

You need to call $app->configure('file.php') in your bootstrap/app.php file to enable them.
So if you have a lot of config files you must add another line indicating the config file name and this method will be a little messy.

Usage

Just download the ConfigServiceProvider file, put it on the App\Providers folder and add the following line in your bootstrap/app.php file to register the provider and that's all, you are ready to go:

$app->register(App\Providers\ConfigServiceProvider::class);

How

The ConfigServiceProvider automatically search and validates if the config folder exists and map all the files in it, then will register all the folder configuration files, if the folder does not exists is throwing a FileNotFoundException.

<?php
namespace App\Providers;
use Illuminate\Support\Facades\App;
use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
class ConfigServiceProvider extends ServiceProvider
{
/**
* The config folder name.
*
* @var string
*/
const CONFIG_FOLDER_NAME = 'config';
/**
* Register all the application config files.
*
* @return void
*/
public function register()
{
$configPath = App::basePath(self::CONFIG_FOLDER_NAME);
if (!is_dir($configPath)) {
throw new FileNotFoundException("The config folder is missing.\nCreate it on the root folder of your project and add the config files there.");
}
collect(scandir($configPath))->each(function ($item, $key) {
App::configure(basename($item, '.php'));
});
}
}
@amackiewicz
Copy link

This - although handy - is super wrong performance way. Scanning directory via php is not so efficient (probably thats the reason why Lumen developers didn't implement that) :)

@typoworx-de
Copy link

Wouldn't it be possible and more efficient to load a given config only on demand by f.e.

config('my-package.foo');

Whereas the config would be config/my-package.php.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment