Does Nette duplicate or reuses services?

4 years ago

meridius
Member | 34
+
0
-

Suppose I have this code:

services:
    - MyService
    - IMyEntityFactory
class MyEntity extends \Nette\Object {

    public function __construct(MyService $myService) {
        ...
    };

}

interface IMyEntityFactory {

    /** @return MyEntity */
    public function create();

}
...
/** @var IMyEntityFactory */
private $myEntityFactory;

...

$a = $this->myEntityFactory->create();
$b = $this->myEntityFactory->create();

The question is: How many instances of MyService will be created?

4 years ago

David Grudl
Nette Core | 6887
+
0
-

Each create() creates new instance.

For reusing create interface with method get() instead of create().

4 years ago

jiri.pudil
Member | 881
+
+2
-

Two instances of MyEntity will be created, but only one instance of MyService.

4 years ago

meridius
Member | 34
+
0
-

Thank you @jiri.pudil I was hoping for that.

Thank you @DavidGrudl but I hope, you're mistakenly reffering to MyEntity, while I was asking about number of MyService after the two ->create() calls.

Last edited by meridius (2015-09-14 09:39)

4 years ago

David Grudl
Nette Core | 6887
+
0
-

Yeah, I got it wrong.