File: environments.md

package info (click to toggle)
php-di 7.1.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 2,932 kB
  • sloc: php: 10,572; makefile: 42; xml: 17; sh: 10; pascal: 5
file content (69 lines) | stat: -rw-r--r-- 1,419 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
---
layout: documentation
current_menu: environments
---

# Injections depending on the environment

You may want to inject different parameters or objects according to the environment, for example:

```php
<?php
return [
    // These values change according to the environment
    'db.host' => 'localhost',
    'db.port' => 3336,

    'DbAdapter' => DI\create()
        ->constructor(DI\get('db.host'), DI\get('db.port')),
];
```

To achieve this, you can create a main `config.php` file and have small configuration files for each environment:

```php
<?php
// config.prod.php
return [
    'db.host' => '178.231.21.29',
    'db.port' => 5000,
];
```

```php
<?php
// config.dev.php
return [
    'db.host' => 'localhost',
    'db.port' => 3336,
];
```

```php
<?php
// config.php
return [
    'DbAdapter' => DI\create()
        ->constructor(DI\get('db.host'), DI\get('db.port')),
];
```

Then you can configure your container to including the correct files:

```php
$builder = new ContainerBuilder();

// Main configuration
$builder->addDefinitions("config.php");

// Config file for the environment
$builder->addDefinitions("config.$environment.php");

$container = $builder->build();
```

## Compilation

If you configure PHP-DI to be compiled you need to compile each environment into a separate file to avoid mixups.

Read the [Performances](performances.md) documentation to learn about compiling the container.