File: inject-on-instance.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 (61 lines) | stat: -rw-r--r-- 1,726 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
---
layout: documentation
current_menu: inject-on-instance
---

# Inject on an existing instance

*Feature introduced in PHP-DI 3.3*

The standard way of using a container is to get an object from it, with all its dependencies injected:

```php
$object = $container->get('foo');
```

But in some situations, you don't have the control of the creation of an object, yet **you want to resolve its dependencies**.

PHP-DI offers the `injectOn` method:

```php
// $object is an instance of some class

$container->injectOn($object);
```

Now, `$object` has all its dependencies injected (through setter injections and property injections).


## Constructor injection

PHP-DI will not perform any constructor injection (because the instance is already created).

If you create the object yourself, you'll have to do the constructor injection yourself:

```php
$object = new MyClass($someDependency, $someOtherDependency);
$container->injectOn($object);
```

If you get the object from some library/framework, then just call `injectOn()`


### Why?

Hopefully, that will help to integrate PHP-DI with other frameworks:

- **MVC frameworks** (Symfony, Zend Framework, …): inject dependencies of the controller, in the controller itself.
- **Tests** (PHPUnit, …): inject tools in your test class, for example a logger, a timer (for performance test), **the entity manager** (for integration tests), …

Example:

```php
class MyController {
    public function __construct() {
        // get container ...
        $container->injectOn($this);
    }
}
```

**Of course**, the preferred method is still to use `$container->get()`. But sometimes you can't get to the root of the framework to intercept the creation of your objects.