File: autowiring.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 (76 lines) | stat: -rw-r--r-- 2,388 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
70
71
72
73
74
75
76
---
layout: documentation
current_menu: autowiring
---

# Autowiring

*Autowiring* is an exotic word that represents something very simple: **the ability of the container to automatically create and inject dependencies**.

In order to achieve that, PHP-DI uses [PHP's reflection](http://php.net/manual/book.reflection.php) to detect what parameters a constructor needs.

Autowiring does not affect performance when [compiling the container](performances.md).

Let's take this example:

```php
class UserRepository
{
    // ...
}

class UserRegistrationService
{
    public function __construct(UserRepository $repository)
    {
        // ...
    }
}
```

When PHP-DI needs to create the `UserRegistrationService`, it detects that the constructor takes a `UserRepository` object (using the [type declarations](http://www.php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration)).

**Without any configuration**, PHP-DI will create a `UserRepository` instance (if it wasn't already created) and pass it as a constructor parameter. The equivalent raw PHP code would be:

```php
$repository = new UserRepository();
$service = new UserRegistrationService($repository);
```

As you can imagine, it's very simple, doesn't require any configuration, and it just works!

## Configuration

**Autowiring is enabled by default.** You can disable it using the container builder:

```php
$containerBuilder->useAutowiring(false);
```

## Limitations

PHP-DI won't be able to resolve cases like this:

```php
class Database
{
    public function __construct($dbHost, $dbPort)
    {
        // ...
    }

    public function setLogger(LoggerInterface $logger)
    {
        // ...
    }
}
```

- it will not know what parameters to give to the constructor (since there is no type-hinting for an object)
- `setLogger()` will not be called

For those classes, you will need to use `DI\autowire()` in [PHP definitions](php-definitions.md) to declare explicitly what to inject.

PHP-DI is also unable to use Reflection on any PHP-internal classes like such that provide access to extension capabilities.
Examples include `Memcached`, `Gearman`, any `Curl*` classes, anything from the SPL classes like `RecursiveIteratorIterator`, and so on.
If you want to instantiate any class provided by the PHP engine or an extension, you have to provide explicit constructor parameters to PHP-DI.