|
| 1 | +--- |
| 2 | +layout: default |
| 3 | +title: Basic Usage |
| 4 | +description: Basic usage of the league/config library |
| 5 | +--- |
| 6 | + |
| 7 | +# Basic Usage |
| 8 | + |
| 9 | +There are three steps to using this library: |
| 10 | + |
| 11 | +- [Defining the configuration schema](/1.0/schemas/) |
| 12 | + - The overall structure of the configuration |
| 13 | + - Required options, validation constraints, and default values |
| 14 | +- [Applying user-provided values](/1.0/setting-values/) against the schema |
| 15 | +- [Reading the validated options](/1.0/reading-values/) and acting on them |
| 16 | + |
| 17 | +## Example |
| 18 | + |
| 19 | +Simply define your configuration schema, set the values, and then fetch them where needed: |
| 20 | + |
| 21 | +```php |
| 22 | +<?php |
| 23 | + |
| 24 | +use League\Config\Configuration; |
| 25 | +use Nette\Schema\Expect; |
| 26 | + |
| 27 | +// Define your configuration schema |
| 28 | +$config = new Configuration([ |
| 29 | + 'database' => Expect::structure([ |
| 30 | + 'driver' => Expect::anyOf('mysql', 'postgresql', 'sqlite')->required(), |
| 31 | + 'host' => Expect::string()->default('localhost'), |
| 32 | + 'port' => Expect::int()->min(1)->max(65535), |
| 33 | + 'database' => Expect::string()->required(), |
| 34 | + 'username' => Expect::string()->required(), |
| 35 | + 'password' => Expect::string()->nullable(), |
| 36 | + ]), |
| 37 | + 'logging' => Expect::structure([ |
| 38 | + 'enabled' => Expect::bool()->default($_ENV['DEBUG'] == true), |
| 39 | + 'path' => Expect::string()->assert(function ($path) { return \is_writeable($path); })->required(), |
| 40 | + ]), |
| 41 | +]); |
| 42 | + |
| 43 | +// Set the values somewhere |
| 44 | +$userProvidedValues = [ |
| 45 | + 'database' => [ |
| 46 | + 'driver' => 'mysql', |
| 47 | + 'port' => 3306, |
| 48 | + 'host' => 'localhost', |
| 49 | + 'database' => 'myapp', |
| 50 | + 'username' => 'myappdotcom', |
| 51 | + 'password' => 'hunter2', |
| 52 | + ], |
| 53 | + 'logging' => [ |
| 54 | + 'path' => '/var/log/myapp.log', |
| 55 | + ], |
| 56 | +]; |
| 57 | + |
| 58 | +// Merge those values into your configuration schema: |
| 59 | +$config->merge($userProvidedValues); |
| 60 | + |
| 61 | +// Read the values and do stuff with them |
| 62 | +if ($config->get('logging.enabled')) { |
| 63 | + file_put_contents($config->get('logging.path'), 'Connecting to the database on ' . $config->get('database.host')); |
| 64 | +} |
| 65 | +``` |
0 commit comments