This package allows you to easily inject configuration files into you own classes.
Download this package or install it through Composer:
"require": {
"codezero/configurator": "3.*"
}
Specify an array...
$config = [
'my_setting' => 'some value',
'my_other_setting' => 'some other value'
];
Or refer to a configuration file...
$config = '/path/to/configFile.php';
That configuration file could look like this:
<?php
return [
'my_setting' => 'some value',
'my_other_setting' => 'some other value'
];
Inject a Configurator
implementation in your class. If none is supplied, the default one will be instantiated. The $configurator->load()
method will return a Configuration
object or throw a ConfigurationException
if no valid array could be loaded.
use CodeZero\Configurator\Configurator;
use CodeZero\Configurator\DefaultConfigurator;
class MyClass {
private $config;
public function __construct($config, Configurator $configurator = null)
{
$configurator = $configurator ?: new DefaultConfigurator();
$this->config = $configurator->load($config);
}
}
Create an instance of your class, passing it the configuration array or file:
$myClass = new MyClass($config);
Get configuration values:
$mySetting = $this->config->get('my_setting');
$myOtherSetting = $this->config->get('my_other_setting');
Set configuration values at runtime:
$this->config->set('my_setting', 'some new value');
And that's all there is to it...
If you use Laravel, then you can setup a binding that resolves your class with its configuration automatically. Let's say you have a class Acme\MyApp\MyClass
:
App::bind('Acme\MyApp\MyClass', function($app)
{
// Specify an array...
$config = [
'my_setting' => 'some value',
'my_other_setting' => 'some other value'
];
// Or refer to a configuration file...
$config = '/path/to/configFile.php';
return new \Acme\MyApp\MyClass($config);
});
What if you don't want to hardcode an array or a file path in your bindings, but instead you want to make use of laravel's Config
infrastructure?
Let's imagine that you create a Laravel configuration file at config/myapp.php
. You could then use this in your binding:
$config = $app['config']->get("myapp");
Simple as that...